[英]Dynamically call php object property
In the php 7 docs, there's http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect . 在php 7文档中,有http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect 。 I'm trying to use this to call property dynamically. 我正在尝试使用它来动态调用属性。 This code only prints v1
. 此代码仅打印v1
。 I want it to print v1pqrxyz
我希望它打印v1pqrxyz
How can I do that? 我怎样才能做到这一点? I'm using PHP version 7.0 我正在使用7.0版本的PHP
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};
}
It is not possible the way you constructed it, even if it looks promising. 即使它看起来很有希望,也不可能以这种方式构造它。 But, you could do the following for methods 但是,您可以对方法进行以下操作
$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);
}
and members could be accessed like this 可以像这样访问成员
$arr = [
'v1'
];
foreach ($arr as $member) {
echo $test1->$member;
}
Try to use call_user_func()
尝试使用call_user_func()
foreach ($arr as $value) {
echo call_user_func([$test1,$value]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.