Call php methods with strings

I have two objects. Objects A and B.

A has a method that returns B. And I want to call it dynamically, so I use the line to call the method inside B as follows:

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

But if you do this:

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

This does not work. Any ideas?

+7
string object methods php
source share
1 answer

You cannot do that. $method can only contain the name of method A Read about variable functions . You could have variables like

 $method1 = 'getB'; $method2 = 'someMethod'; $a->$method1()->$method2(); 

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

The question is, what is your ultimate goal?

+18
source share

All Articles