Evaluate object to a boolean

前端 未结 6 1484
醉话见心
醉话见心 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 09:49

    Sorry for being late, but I just played with similar task and have made some kind of a hack/workaround. Notice "$object" pattern which calls __toString method.

    class tst {
      public $r = true;
      function __toString() { return $this->r ? "1" : "0"; }
    }
    $object = new tst();
    $object->r = true;
    echo '
    1: '; if ("$object") echo 'true!'; else echo 'false!'; // "$object" becomes "1" == true //echo "$object" ? 'true!' : 'false!'; $object->r = false; echo '
    0: '; echo "$object" ? 'true!' : 'false!'; // "$object" becomes "0" == false

    Output:

    1: true!
    0: false!
    

提交回复
热议问题