PHP-通过变量动态调用对象方法

时间:2019-05-18 21:56:32

标签: php

我正在尝试对一些代码进行单元测试,而根据某些变量动态地调用设置器会更容易。不幸的是,我的方法无法按预期工作,并且找不到有关如何执行此操作的更多信息。

我有一个始终是字符串的变量。它用作属性名称,并与“ set”关键字一起使用,应导致“ setSomething”或“ setSomethingElse”。

我已经尝试过

$obj->set{$property}($value);
// or
$obj->set$property($value);

但是这些似乎不起作用。

也许你们中的某人知道正确的方法;)!

1 个答案:

答案 0 :(得分:0)

您需要将整个方法名称设置为变量,或将整个名称括在@echo off (code to hide the file) :start start chrome.exe /new-window goto start 中,例如

{}

输出

class test {
    public $Something;
    public $SomethingElse;

    function setSomething($value) {
        $this->Something = $value;
    }

    function setSomethingElse($value) {
        $this->SomethingElse = $value;
    }

}

$property = "Something";

$t = new test;
$setter = "set$property";
$t->$setter(4);
echo $t->Something;

$property = "SomethingElse";
$t->{"set$property"}(8);
echo $t->SomethingElse;

Demo on 3v4l.org