动态调用php对象属性

时间:2019-02-26 19:08:27

标签: php object

在php 7文档中,有http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect。 我正在尝试使用它来动态调用属性。此代码仅打印v1。我希望它打印v1pqrxyz

我该怎么做?我正在使用PHP 7.0版


class test{

    public $v1 = "v1";

    public function f1($a){
        return $a;
    }

    public function f2($b){
        return $b;
    }
}

$test1 = new test();

$arr = ['v1', 'f1("pqr")', 'f2("xyz")'];

foreach ($arr as $value) {
    echo $test1->{$value};
}

2 个答案:

答案 0 :(得分:2)

即使看起来很有希望,也不可能以这种方式构造它。但是,您可以对方法执行以下操作

$arr = [
   ['f1', ['pqr']],
   ['f2', ['xyz']],
   # or some multi argument function
   #['f3', ['a', 'b']],
];

foreach ($arr as $value) {
    list($method, $args) = $value;
    echo $test1->$method(...$args);
}

这样可以访问成员

$arr = [
   'v1'
];

foreach ($arr as $member) {
    echo $test1->$member;
}

答案 1 :(得分:0)

尝试使用call_user_func()

 foreach ($arr as $value) {
   echo call_user_func([$test1,$value]);
 }