1

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};
}
1
  • You would need eval or regular expressions to handle string expressions like 'f1("pqr")'. Both are unsafe and/or error prone. You should not do it. Whenever possible use ['v1', ['f1', ['arg1', 'arg2']], 'v2'] instead. Commented Feb 26, 2019 at 19:25

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use call_user_func()

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

1 Comment

I'm getting error when doing it this way Warning: call_user_func() expects parameter 1 to be a valid callback, class 'test' does not have a method 'f1()'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.