Monday, 6 September 2010

PHP: Call to a member function on a non-object

PHP LogoRan across a PHP thinking in Java problem today. Say you have some code like this:



class MyClass{
private $myObject;

public function MyClass(){
$myObject = new MyObject()
}

}
As soon as the $myObject variable is accessed the following error is thrown: Call to a member function on a non-object.



What?????



This is PHP not Java nimrod. :) $myObject is not getting initialized because the syntax is incorrect. Try this:

class MyClass{
private $myObject;

public function MyClass(){
$this->myObject = new MyObject()
}

}
That should fix it right up. This sort of stuff always happens to me as I bounce between languages. lol.

No comments:

Post a Comment