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?

1 Answer 1

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

3 Comments

Great Silvio! This was the missing thing, I haven't seen after 10 hours in front of the monitor! thx
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?
Yes of course, it works exactly the same: $varname = "foo"; $this->$varname = "bar"; // now $this->foo == "bar";

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.