对象本身的 __isset() 魔术函数
我知道你可以这样做
class Object
{
private $ar;
public function __isset($name)
{
return isset($this->ar[$name]);
}
}
,然后可以用来执行以下操作
$obj = new Object();
if (isset($obj->name)) { /* ... */ }
但是有没有办法做到这一点
$obj = new Object();
if (isset($obj)) { /* .... */ }
,我可以使用 __isset()$obj 状态的返回code> 对象本身的魔术方法。
I know you can do this
class Object
{
private $ar;
public function __isset($name)
{
return isset($this->ar[$name]);
}
}
which can then be used to do the following
$obj = new Object();
if (isset($obj->name)) { /* ... */ }
However is there a way to do this
$obj = new Object();
if (isset($obj)) { /* .... */ }
Where i can control the return of $obj
status using the __isset()
magic method on the object it self.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只能定义一个新的全局函数
myIsset()
或类似的函数来执行此操作。当使用
isset
检查变量$obj
时,PHP 根本不会与该变量可能引用的对象进行交互。You could only define a new global function
myIsset()
or something like it to do this.When checking the variable
$obj
withisset
PHP doesn't interact with the object that might be referenced by the variable at all.你不能,因为它没有任何意义(至少没有按照
isset()
的使用方式)。因此,只要isset($obj)
指向某个对象并且不为 NULL/未定义,它就始终为 true。You cannot, because it would not make any sense (at least not in the way
isset()
is meant to be used). Soisset($obj)
is always true as long as it points to some object and not NULL/undefined.魔术方法
__isset
不应该以这种方式使用。根据 PHP 手册:
“__isset() 是通过调用 isset( ) 或empty() 无法访问的属性。”
Magic method
__isset
is not intended to be used that way.According to PHP manual:
"__isset() is triggered by calling isset() or empty() on inaccessible properties."