Home » Php » Calling php methods with strings

Calling php methods with strings

Posted by: admin July 12, 2020 Leave a comment


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();

It doesn’t work. Any ideas?

How to&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';


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?