0

为了处理到字符串的转换, __toString() 存在于 php.ini 中。但是,如果我有一个实例化的对象,例如:

$myObj = new Object();
$myObj->doSomeThings();

if ($myObj) {
    // Some stuff to do here
}

在 if 条件中评估 $myObj 时,如何告诉 PHP 该做什么?

我很好奇的主要原因是,我想要一个可链接的方法,它也可以在 if 语句中直接有条件地评估。

if ($myObj->chainMethodA($var)->chainMethodA($var2)->chainMethodB($var)) {

鉴于所有这些方法都可以:

return $this;

如何根据类属性处理对象的布尔评估,例如:

$this->switch = true;

我知道我总是可以这样

if ($myObj->chainMethodA($var)->chainMethodA($var2)->chainMethodB($var)->switch) {

但我更愿意自动处理。

4

1 回答 1

0

This is a matter of code preference.

if you are using method chaining, you can chain them in the loop as you sugested. this originates for ugly IF statements but works fine.

another way to do this is call every method and then check for the switch (using on not a getter).

so you have this:

$myObj = new Object();
$myObj->doSomeThings();
$myObj->chainMethodA($var)->chainMethodA($var2)->chainMethodB($var);

for the if you can:

if( $myObj->switch ){
...
}

or

if( $myObj->switchState() ){
..
}

however, what i sugest is wrap your functions in another bool method, or another class, so all you have to do is:

$myObj = new Object();
if( $myObj->doAlotOfThings($var1,$var2) ){

}
于 2013-05-07T00:20:16.410 回答