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
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.
See this example.
Unlike common functions can be defined only in class scope and invoked automatically on specific events such as: inaccessible method invocation, class serialization, when unset()
used on inaccessible properties and so on. See also this official documentation: Overloading.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…