0

I'am trying to call a public funtion of a class with variables(php7). Therfore I do:

$module = 'frontend\\modules\\rest\\models\\Member';
$action = 'view_profile'

$response = new $module();
$response = $response1->$action;

By calling $response1->$action I get the following error:

Undefined property: frontend\modules\rest\models\Member::$view_profile

I see that the systems try to call ...Member\$view_profile and this will not work. But why is the '$' before view_profile. I've tried several variantes, but the error with the $view_profile is always there. What is wrong with this approach?

Perino
  • 608
  • 9
  • 30

1 Answers1

1

Check out this other reply: OOP in PHP: Class-function from a variable? (cannot comment, sorry...)

Anyway, this is what you are after: http://php.net/manual/en/functions.variable-functions.php

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

So I guess the only thing missing is the "()" after

$response1->$action;
  • Great Silvio! This was the missing thing, I haven't seen after 10 hours in front of the monitor! thx – Perino Apr 10 '18 at 17:21
  • Silvio, is it also possible to set a public class variable also this way? I mean with a generic variable like $foo->$var? How can I set a class variable with $var this way? – Perino Apr 13 '18 at 05:24
  • Yes of course, it works exactly the same: $varname = "foo"; $this->$varname = "bar"; // now $this->foo == "bar"; – Silvio Porcellana Apr 16 '18 at 10:11