Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling php methods with strings

I have two objects. Object A and B.

A has a method which returns B. And I want to call this dynamically so I use a string for calling a method inside of B like so:

$method = 'getB()->someMethod';

But if do this:

$a = new A();
$a->$method();

It doesn't work. Any ideas?

like image 354
rix501 Avatar asked Oct 15 '10 14:10

rix501


People also ask

How do you call a function from a string in PHP?

Just use this: $str = "abcdefg". foo().

How do you call a method in a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

What is __ call () in PHP?

Method overloading ¶ __call() is triggered when invoking inaccessible methods in an object context. __callStatic() is triggered when invoking inaccessible methods in a static context. The $name argument is the name of the method being called.


1 Answers

You cannot do it like that. $method can only contain the name of a method of A. Read about variable functions. You could have to variables though, e.g.

$method1 = 'getB';
$method2 = 'someMethod';

$a->$method1()->$method2();

But probably it would be better to rethink the problem, consider another structure of your code and/or having a look at design patterns.

The question is: What is your ultimate goal?

like image 152
Felix Kling Avatar answered Oct 14 '22 05:10

Felix Kling