[php] Call to a member function on a non-object

So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.

class PageAtrributes 
{
  private $db_connection;
  private $page_title;

    public function __construct($db_connection) 
    {
        $this->db_connection = $db_connection;
        $this->page_title = '';
    }

    public function get_page_title()
    {
        return $this->page_title;
    }

    public function set_page_title($page_title)
    {
        $this->page_title = $page_title;
    }
}

Later on I call the set_page_title() function like so

function page_properties($objPortal) {    
    $objPage->set_page_title($myrow['title']);
}

When I do I receive the error message:

Call to a member function set_page_title() on a non-object

So what am I missing?

This question is related to php

The answer is


I realized that I wasn't passing $objPage into page_properties(). It works fine now.


function page_properties($objPortal) {    
    $objPage->set_page_title($myrow['title']);
}

looks like different names of variables $objPortal vs $objPage


It could also mean that when you initialized your object, you may have re-used the object name in another part of your code. Therefore changing it's aspect from an object to a standard variable.

IE

$game = new game;

$game->doGameStuff($gameReturn);

foreach($gameArray as $game)
{
   $game['STUFF']; // No longer an object and is now a standard variable pointer for $game.
}



$game->doGameStuff($gameReturn);  // Wont work because $game is declared as a standard variable.  You need to be careful when using common variable names and were they are declared in your code.

you can use 'use' in function like bellow example

function page_properties($objPortal) use($objPage){    
    $objPage->set_page_title($myrow['title']);
}

Either $objPage is not an instance variable OR your are overwriting $objPage with something that is not an instance of class PageAttributes.


There's an easy way to produce this error:

    $joe = null;
    $joe->anything();

Will render the error:

Fatal error: Call to a member function anything() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23

It would be a lot better if PHP would just say,

Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define anything() in on line <##>.

Usually you have build your class so that $joe is not defined in the constructor or


I recommend the accepted answer above. If you are in a pinch, however, you could declare the object as a global within the page_properties function.

$objPage = new PageAtrributes;

function page_properties() {
    global $objPage;
    $objPage->set_page_title($myrow['title']);
}