在一个对象上以文本形式执行多种方法

时间:2019-06-07 10:21:56

标签: php

这些是我的示例类:

class First {
   public function getSecond();
}

class Second {
   public function getThird();
}

class Third {}

如果我想从文本中执行一种方法,我可以:

$first = new First();

$method = 'getSecond';

$first->$method();

这很好,但是我想在对象上运行几种方法。

不幸的是,我在数组中有这些方法:

$first = new First();

$methods = array('getSecond', 'getThird');

那我该怎么做:

$first = new First();

$methodsInOneLine = implode('()', $methods);

$first->$methods;

但是,这当然行不通...

1 个答案:

答案 0 :(得分:0)

您需要在for循环中迭代该数组,并且需要像下面这样一个接一个地访问元素。

$methods = array('getSecond', 'getThird');
$first = new First();

for($i=0;$i<count($methods);i++){

    $methodsInOneLine = $methods[$i];
    $first->$methodsInOneLine;    
}
相关问题