将对象评估为布尔值 [英] Evaluate object to a boolean

查看:176
本文介绍了将对象评估为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

class MyClass
{
  private $var1 = "apple";
  private $var2 = "orange";
}

$obj = new MyClass();

if($obj) { 
  // do this
}
else {
  // do that
}

PHP将我的对象评估为true,因为它有成员变量。这个逻辑可以以某种方式被覆盖吗?换句话说,我可以控制我们类的对象在处理为布尔值时将要计算的对象。

PHP evaluates my object to true because it has member variables. Can this logic be overridden somehow? In other words, can I have control over what an object of my class will evaluate to when treated as a boolean?

推荐答案


PHP将我的对象评估为true,因为它有成员变量。

PHP evaluates my object to true because it has member variables.

这是不正确的。 PHP实际上评估 $ obj true ,因为它包含一个对象。它与对象的内容无关。您可以通过从类定义中删除成员来验证这一点,但它不会对选择if / else的哪个分支产生任何影响。

This is incorrect. PHP actually evaluates $obj as true because it holds an object. It has nothing to do with the contents of the object. You can verify this by removing the members from your class definition, it won't make any difference in which branch of the if/else is chosen.

使PHP将一个变量评估为true,如果它持有一个对象。您必须先将以下之一分配给变量:

There is no way of making PHP evaluate a variable to true if it holds to an object. You'd have to assign one of the following to the variable first:

null
array()
""
false
0

这篇关于将对象评估为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆