Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call methods with variables?

Tags:

php

eval

Can I do the following in PHP?

$lstrClassName  = 'Class';
$lstrMethodName = 'function';
$laParameters   = array('foo' => 1, 'bar' => 2);

$this->$lstrClassName->$lstrMethodName($laParameters);

The solution I'm using now, is by calling the function with eval() like so:

eval('$this->'.$lstrClassName.'->'.$lstrMethodName.'($laParameters);');

I'm curious if there is a beter way to solve this.

Thanks!

like image 561
pascalvgemert Avatar asked Apr 05 '12 14:04

pascalvgemert


People also ask

How do you call a method using variables?

You could try something like: Method m = obj. getClass(). getMethod("methodName" + MyVar); m.

Can I call a variable from another method Java?

You can't. Variables defined inside a method are local to that method. If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).

Can methods access variables in the main method?

Because the variable that you have declared in main method is a local variable and accessible to main method only. For accessing variable between methods declare it as an instance varibale, which is accessible by all class members.


2 Answers

You don't need eval to do that ... depending on your version

Examples

class Test {
    function hello() {
        echo "Hello ";
    }

    function world() {
        return new Foo ();
    }
}

class Foo {

    function world() {
        echo " world" ;
        return new Bar() ;
    }

    function baba() {

    }
}

class Bar {

    function world($name) {
        echo $name;
    }


}


$class = "Test";
$hello = "hello";
$world = "world";
$object = new $class ();
$object->$hello ();
$object->$world ()->$world ();
$object->$world ()->$world ()->$world(" baba ");

Output

Hello World baba

And if you are using PHP 5.4 you can just call it directly without having to declare variables

You might also want to look at call_user_func http://php.net/manual/en/function.call-user-func.php

like image 80
Baba Avatar answered Sep 28 '22 15:09

Baba


Did you try your code? The best way to find out if something will work is by trying it. If you do try it, you will find that yes, it does work (assuming that $this has a property called Class which is an instance of an object that defines a method called function).

There are also the two functions call_user_func() and call_user_func_array()

like image 31
DaveRandom Avatar answered Sep 28 '22 16:09

DaveRandom