gpt4 book ai didi

php - isset() 和 __isset() 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 12:08:37 27 4
gpt4 key购买 nike

我需要了解魔术函数 __isset() 和普通函数 isset()。实际上 php 语言构造 isset() 和 php 魔术方法 __isset() 之间的真正区别是什么?当我用谷歌搜索时,他们告诉我 __isset() 是一个神奇的功能。 php中常用的php函数和魔术函数有什么区别?

最佳答案

isset()

它是一种检查变量或类属性初始化的语言结构:

$a = 10;

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

class Test
{
public $prop = 10;
}

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

__isset()

这是一个神奇的方法,当 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(),但它与魔术方法无关。

this example .


Magic Methods

与普通函数不同,只能在类范围内定义并在特定事件上自动调用,例如:不可访问的方法调用、类序列化、当 unset() 用于不可访问的属性等。另见官方文档:Overloading .

关于php - isset() 和 __isset() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21227585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com