user2869411
user2869411

Reputation:

PHP Class and Function from variable

I am working on a simple router program in PHP. Here is my function

    private function dispatch($dest)
    {
        $goto = explode("@", $dest);

        $controller = $goto[0];
        $action = $goto[1];

        $clocation = require_once("../app/controllers/$controller.php");
        $c = new $controller;


    }

Everything works to that point. But, I want to return the results of the action (a method within the class that is instantiated as $c. I tried :

return $c->$action

but that doesn't work. Is there a way to do this, or do I need to try a different approach all together?

thanks

Upvotes: 0

Views: 26

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Try this

return $c->$action();

With the () for a method/function call. Otherwise PHP thinks it's a dynamic property of $c

You can test this like so:

class foo{

    public $bar = 'bar';

    function test(){ return 'test'; }
}

$foo = new foo();

$bar = 'bar';
$test = 'test';

echo $foo->$bar . PHP_EOL;
echo $foo->$test() . PHP_EOL;

Outputs

bar
test

Try it online

And $foo->$test would give you this notice

 <br />
 <b>Notice</b>:  Undefined property: foo::$test in <b>[...][...]</b> on line     <b>16</b><br />

Which means you either didn't mention it, don't have error reporting on, or your class has a property with the same name as that method.

Upvotes: 1

Related Questions