Home » Php » Calling php methods with strings

Calling php methods with strings

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

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';

$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?