0

This question may sound stupid, but I want this to work. I've got this code:

$data['method'] = 'get';
$this->app->$data['method']();

How can I replace $data['method'] with get but no string. I've tried this, but no luck.

$this->app->{$data['method']}();

Any idea?

4
  • 5
    call_user_func Commented Apr 13, 2018 at 20:17
  • php.net/manual/en/functions.variable-functions.php function example(){ echo "hello"; } $function = "example"; $function(); // will run the function "example" and show "Hello". Commented Apr 13, 2018 at 20:22
  • 1
    Interestingly I also tried what you tried and yes luck. Commented Apr 13, 2018 at 21:26
  • 1
    my bad. I'm sorry guys. the last code does work. a little drunk last night and didn't realize that I had the wrong piece in my editor while wrote the right one here... Commented Apr 14, 2018 at 5:56

2 Answers 2

1

The last code you posted should work, if you're using PHP 5.4.0 and higher.

<?php

class A {
    public function foo() {
        echo "yes!";
    }
}

class B {
    public function run() {

        $this->a = new A;

        $data = [];
        $data['method'] = "foo";        
        $this->a->{$data['method']}();        

    }
}

$b = new B;
$b->run();
// Prints "yes!"
Sign up to request clarification or add additional context in comments.

Comments

1

This will work:

call_user_func(array($this->app, $data['method']));

good luck.

Comments

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.