Evaluate object to a boolean

前端 未结 6 1491
醉话见心
醉话见心 2020-12-17 08:58

Consider the following:

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

$obj = new MyClass();

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


        
6条回答
  •  渐次进展
    2020-12-17 10:01

    No, you can't. Unfortunately boolean casting in php is not modifiable, and an object will always return true when converted to a boolean.

    Since you clearly have some logic you mean to place in that control statement, why not define a method on your object (say "isValid()" ) that checks the conditions you wish to check, and then replace:

    if ($obj)
    

    with:

    if ($obj->isValid())
    

提交回复
热议问题