2

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 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

So the execution of the script doesn't stop? It just logs the error and keeps going. Correct?
Unfortunately, for some reasons PHP developers felt that allowing a programmer to ignore errors can be useful.
1

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.