Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 256
Scott Gottreu Avatar asked Sep 10 '08 16:09

Scott Gottreu


3 Answers

It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?

As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:

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

This function will only accept PageAtrributes for the first parameter.

like image 75
Allain Lalonde Avatar answered Nov 02 '22 20:11

Allain Lalonde


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

like image 42
David Urry Avatar answered Nov 02 '22 21:11

David Urry


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

like image 7
dipole_moment Avatar answered Nov 02 '22 21:11

dipole_moment