0

考虑这个类:


class Test {  
    public $obj;  

function __construct ($obj) {  
    $this->obj = $obj;  
}  

$obj 有自己的公共函数。我通过我的代码调用它$t = new Test($obj); $t->obj->do();

我想让 $obj 为空,而不触发错误。如果未明确设置函数,是否可以使用 PHP 的魔术函数执行一些技巧以始终返回 false ?另外,PHP < 5.3 会有解决方案吗?

4

1 回答 1

2

我现在无法对此进行测试,但这可以工作:

class default {
      public function __call($name, $arguments) {
             return false;
      }
}

class Test {
      public $obj;
      public function __construct($obj = NULL) {
           if($obj === NULL) $this->obj = new default;
           else $this->obj = $obj
      }
}
于 2010-12-18T15:17:47.890 回答