Page 1 of 1

Throwing error when calling a member function on a null var

Posted: Tue Jan 09, 2007 12:35 am
by ario
I've been having problems lately with calling member functions on variables whose values may not have changed from null yet due to other bugs. I'm running PHP 5.1.2 and this is really problematic because it doesn't throw any error, it just stops execution and prints a blank page.

Three closely related problems do in fact throw errors:

Code: Select all

$foo = null;
echo $foo->field;
The above will throw a notice: "Trying to get property of non-object". Or,

Code: Select all

echo $foo->field;
The above will throw a notice: "Undefined variable: foo". Or,

Code: Select all

echo $foo->method()
The above will also throw the same notice: "Undefined variable: foo".

However, this piece of code

Code: Select all

$foo = null;
echo $foo->method();
will throw no error and just make the screen blank. I'd really like to be able to catch this type of error, but extensive searching in the usual places (google, PHP documentation and forums) has turned up nothing. Can anyone help?

Posted: Tue Jan 09, 2007 12:40 am
by feyd

Code: Select all

[feyd@home]>php -r "$foo = null; $foo->method();"
Fatal error: Call to a member function method() on a non-object in Command line code on line 1
As you can see, it throws a fatal error. These often happen before any code has actually been run. It cannot be caught.

Posted: Tue Jan 09, 2007 12:43 am
by ario
Thanks, but I'm still confused as to how then you managed to get that error message. Did you somehow execute that from the command line?

Posted: Tue Jan 09, 2007 12:50 am
by feyd
The example posted was from the command line yes, however it's also possible to see it on a web page. You simply have to have error_reporting and display_errors set correct before the script is loaded. On Apache servers this can often be set via .htaccess if necessary.

Posted: Tue Jan 09, 2007 12:51 am
by aaronhall
http://www.php.net/features.commandline wrote:-r <code> Run PHP <code> without using script tags <?..?>

Posted: Tue Jan 09, 2007 12:55 am
by ario
feyd wrote:The example posted was from the command line yes, however it's also possible to see it on a web page. You simply have to have error_reporting and display_errors set correct before the script is loaded. On Apache servers this can often be set via .htaccess if necessary.

Thanks; I should have figured (and mentioned) that the .ini file had something to do with it, because I just reinstalled PHP a couple days ago and mistakenly backed up the wrong ini file, so those settings had changed. That fixed it.