动态调用基于测试的php对象方法?

时间:2012-09-24 04:16:16

标签: php object dynamic methods

有人能告诉我是否可以根据测试的成功调用php对象的方法?例如下面......

正常使用:

$obj = new obj;
$obj->call()
    ->successive()
    ->methods();

运行测试以查看是否应该调用方法:

$obj = new obj;
$obj->call()
    ( if ($a) ? ->successive() : '')
    ->methods();

有没有办法让上面的第二个例子有效?或者另一种方法可以达到相同的效果?感谢。

3 个答案:

答案 0 :(得分:2)

也许?

$obj = new obj;
$temp = $obj->call();
if ($a) {
   $temp = $temp->successive();
}
$temp->methods();

答案 1 :(得分:1)

也许将方法名称传递给.successive()并将其作为回调处理。

class obj {
  private $is_success;

  public function call() {
     $this->is_success = return_a_boolean();
     return $this;
  }

  public function successive($callback) {
     if ($this->is_success && method_exists($this, $callback)) {
        $this->$callback();
     }
     return $this;
  }

  public function methods() {
      //....
  }
}

$obj = new obj;
$obj->call()
    ->successive('methods');

答案 2 :(得分:0)

如果您在测试失败时执行了回退方法,您可以像这样构建它,我想:

$obj = new obj;
$obj->call()
    ->{ $a ? "successive" : "fallback_method"}()
    ->methods();

这会有帮助吗?您可能希望回退方法看起来像:

function fallback_method() {
    return $this;
}
相关问题