isset()
它是一个检查变量或类属性的初始化的语言结构:
$a = 10;
isset($a); // true
isset($a, $b); // false
class Test
{
public $prop = 10;
}
$obj = new Test;
isset($obj->prop); // true
这是一个魔术方法,当isset()或empty()检查不存在或不可访问的类属性时被调用:
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
区别:
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()结果无论如何将是automatically casted作为bool。
实际上,你可以定义自定义函数__isset(),但它与魔术方法无关。
与普通函数不同,只能在类范围中定义,并在特定事件上自动调用,例如:不可访问的方法调用,类序列化,当unset()用于不可访问的属性等时。另见本官方文档:Overloading。