I noticed that PHP doesn't throw exception when I try to access a property from an object that is NULL. Is this correct? I would expect there would be some kind of error like in other languages.
4 Answers
Nope, just a warning for accessing an undefined member. If you wish, you can add the exception into your class manually with the __get() magic function:
class foo {
public function __get( $name )
{
throw new Exception($name . ' does not exist in foo');
}
}
Now the class will behave how you were expecting.
$bar = new foo();
$x = $bar->something;
echos out:
Fatal error: Uncaught exception 'Exception' with message 'something does not exist in foo' in C:\web\xampp\htdocs\stupid2.php:7 Stack trace: #0 C:\web\xampp\htdocs\stupid2.php(14): foo->__get('something') #1 {main} thrown in C:\web\xampp\htdocs\test.php on line 7
Comments
It reports an error, a notice to be more correct
<?php
error_reporting(-1);
$var = null;
$var->prop;
echo 'Hello!';
results in:
Notice: Trying to get property of non-object in /..../prog.php on line 6
Hello!
2 Comments
You should be getting a PHP Notice Warning, it would look something like this:
PHP Notice: Trying to get property of non-object in [...]
If not, you should check your error settings. While in development, try setting
error_reporting(-1);
in order to see all PHP errors/warnings/notices so that you can fix up your code as best as possible.
Comments
Exception handling is introduced since version 5 and has not been implemented for all in built functions.
If you want to get exceptions you can always check if the variable is null or is not an object and throw a custom exception which can be handled by catch block.
For getting Errors, warnings and notices you can use development version of PHP.ini file. or just search for php.ini file, look for Error handling and logging section in it and set error_reporting to E_ALL, Look-up for display_errors and set it to on. Then restart your web server for the settings to take effect.