isset()和__isset()有什么区别? [英] What is the difference between isset() and __isset()?
问题描述
我需要了解魔术函数__isset()
和普通函数isset()
.其实php语言构造isset()
和php魔术方法__isset()
之间的真正区别是什么?当我在Google上搜索时,他们告诉我们__isset()
是一个魔术函数.普通的php函数和php中的魔术函数有什么区别?
I need to know about magic function __isset()
and normal function isset()
. Actually what is the real difference between php language construct isset()
and php magic method __isset()
? When I google it they told that __isset()
is a magic function. What are difference between common php functions and magic functions in php?
推荐答案
isset()
这是一种用于检查变量或类属性的初始化的语言构造:
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()
这是一种魔术方法,当isset()
或empty()
检查不存在或无法访问的类属性时会调用该方法:
__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
差异:
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()
结果将被自动转换为为bool
.
实际上,您可以定义自定义函数__isset()
,但它与magic方法无关.
Actually you can define custom function __isset()
but it has nothing to do with the magic method.
请参见此示例.
与普通功能不同,只能在类范围内定义并在特定事件上自动调用,例如:不可访问的方法调用,类序列化,在不可访问的属性上使用unset()
时等.另请参见此官方文档:超载.
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.
这篇关于isset()和__isset()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!