试图在函数上调用一组参数

时间:2017-03-15 11:05:25

标签: php oop

我有一个参数数组传递给一个参数数量可变的方法。我完全不知道怎么做。

class Entity {
    protected $realObject;

    public function __call($name, $arguments) {
        // just call this method on the $property, otherwise redefine the method
        // error_log("Called $name");

        // TODO support variable numbers of arguments
        $argc = count($arguments);
        if($argc > 0) {
            return $this->realObject->$name($arguments[0]);
        } else {
            return $this->realObject->$name();
        }
    }

}

我一直在研究各种各样的方法,但似乎找不到将数组转换为变量变量的方法。

3 个答案:

答案 0 :(得分:1)

built-in support for this in PHP >= 5.6(你应该至少运行它)。

E.g:

$parameters = ['parameter1', 'parameter2', 'parameter3'];

function iAcceptManyParameters(...$parameters) {
   foreach ($parameters as $parameter) {
      echo $parameter, "\n";
   }
}

iAcceptManyParameters(...$parameters);

您可以看到它正常工作here

答案 1 :(得分:0)

这是你想要做的吗?

class Entity
{
    protected $myClass;

    public function __construct(string $myClass)
    {
        $this->myClass = new $myClass;
    }

    public function __call($name, $arguments)
    {
        return $this->myClass->$name($arguments);
    }
}

class TestClass
{
    public function foo($msg)
    {
        return $msg;
    }
}

$entity = new Entity('TestClass');
var_dump($entity->foo('bar', 'baz'));
die();

输出:

array(2) {
  [0]=>
  string(3) "bar"
  [1]=>
  string(3) "baz"
}

但根据您的评论Yes, it's an abstraction of somebody else's classes. My object is a copy of their object,为什么不创建您的课程,这会扩展他们的课程?例如class MyEntity extends TheirEntity {...}。然后,您的班级将继承其公共和受保护的属性。方法

答案 2 :(得分:0)

好的,你知道,当你尝试执行你无法访问的所述类的方法时,会调用类的魔术方法__call。所以,在这种情况下:

class Entity {

    protected function realObject($a, $b, $c) {

    }

    public function __call($name, $arguments) {

        $argc = count($arguments);

        if($argc > 0) {
            return $this->$name($arguments[0],$arguments[1],$arguments[2]);
        } else {
            return $this->$name();
        }
    }

}

现在,假设您在此类中实例并尝试调用私有方法

$myEntity = new Entity();

$myEntity->realObject('hello','my','friends');

受保护的方法调用被__call拦截,所以就像你调用了

一样
$myEntity->__call('realObject',['hello','my','friends']);

无论您决定在__call方法中做什么,都取决于您。在我的示例中,它只是将您的调用转发给受保护的方法。

相关问题