Reputation: 442
In the php 7 docs, there's 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
. I want it to print v1pqrxyz
How can I do that? I'm using PHP version 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};
}
Upvotes: 1
Views: 31
Reputation: 2581
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;
}
Upvotes: 2
Reputation: 407
Try to use call_user_func()
foreach ($arr as $value) {
echo call_user_func([$test1,$value]);
}
Upvotes: 0