Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - instanceof v === null

Is there a specific benefit of using instanceof instead of === null before initializing objects in php.

I see code like this all the time in the Zend framework:

if (!self::$_httpClient instanceof Zend_Http_Client) {
        /**
         * @see Zend_Http_Client
         */
        #require_once 'Zend/Http/Client.php';
        self::$_httpClient = new Zend_Http_Client();
    }

    return self::$_httpClient;

But the property cannot be set externally and will therefore be null until set

like image 332
Marty Wallace Avatar asked May 22 '26 17:05

Marty Wallace


2 Answers

The check is a little more definitive if you absolutely want self::$_httpClient to be a Zend_Http_Client and not anything else.

Although good programming may prevent it from being anything else, if the variable were to become a String, int, or an instance of another object it would be corrected where checking for null would not.

like image 78
None Avatar answered May 25 '26 05:05

None


Its correct you can do it with your solution and the "===" but then you cannot check wheather the instance is really an instance of "Zend_Http_Client" perhaps you call another class to $_httpClient then its not NULL and its not working.

In my mind its better to use the internal functions of php to check such things.

like image 24
René Höhle Avatar answered May 25 '26 05:05

René Höhle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!