Showing posts with label PHP Initialization of class properties. Show all posts
Showing posts with label PHP Initialization of class properties. Show all posts

Thursday, 18 September 2014

Difference between isset() and __isset() in PHP

isset()

It is a language construct that checks the initialization of variables or class properties:
$a = 10;

isset($a);     // true
isset($a, $b); // false

class Test
{
    public $prop = 10;
}

$obj = new Test;
isset($obj->prop); // true

__isset()

It is a magic method that is invoked when isset() or empty() check non-existent or inaccessible class property:
class Test
{
    public function __isset($name) {
        echo "Non-existent property '$name'";
    }
}

$obj = new Test;
isset($obj->prop); // prints "Non-existent property 'prop'" and return false

Difference:

           isset()                               __isset()
Language construct                    | Magic method
                                      |
Always return bool                    | Result depends on custom logic*
                                      |
Must be invoked in code               | Called automatically by event
                                      |
Unlimited number of parameters        | Has only one parameter
                                      |
Can be used in any scope              | Must be defined as method**
                                      |
Is a reserved keyword                 | Not a reserved keyword
                                      |
Can't be redefined (Parse error)      | Can be redefined in extended class***
__isset() result anyway will be automatically casted as bool.
Actually you can define custom function __isset() but it has nothing to do with the magic method.