PHP 中的empty() 函数有什么神奇之处?
它不应该是 __isset
,因为 isset()
与 empty()
不同
It should not be __isset
,because isset()
is not the same thing as empty()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如此页面:
empty() 没有专用的魔术方法。
如果 __isset() 返回 true,empty() 将调用 __get() 来检查属性的值。
As it says on this page:
There is no dedicated magic-method for empty()
If __isset() returns true, empty() will then invoke __get() to check the value of the property.
作为 Inspire 答案的补充:
输出的
含义是第一个属性 (foo)empty() 仅调用了返回 false 的 __isset() ->
空($foo->foo)===true
对于第二个属性 (bar),调用了 __isset() 并返回 true。然后通过 __get() 获取该属性并将其解释为布尔值(请参阅 http:// docs.php.net/language.types.type-juggling)。由于 (bool)0 为
false
,empty() 也会为empty($foo->bar)
返回true
As an addition to Inspire's answer:
the output is
meaning for the first property (foo) empty() only invoked __isset() which returned false ->
empty($foo->foo)===true
For the second property (bar) __isset() was invoked and it returned true. Then the property is fetched via __get() and interpreted as a boolean value (see http://docs.php.net/language.types.type-juggling). And since (bool)0 is
false
, empty() also returnstrue
forempty($foo->bar)
我认为一般来说,您会发现以下是 PHP 的等效内容:
例如,如果变量是字符串,则这将检测到该字符串为空。对于大多数原始类型(如果不是全部),它的工作方式类似。
I think in general you'll find that the following is the PHP equivalent:
If, for example, the variable is a string, this would detect that the string was empty. It would work similarly for most primitive types (if not all).
如果您只是测试类变量是否存在,
property_exists()
不适合您吗?doesn't
property_exists()
work for you if you're just testing if a class variable exists?