7

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?

2
  • Shouldn’t you call $a->getB() first to get B? Commented Oct 15, 2010 at 15:03
  • Why your method doesn't have ()? Commented Oct 15, 2010 at 15:07

1 Answer 1

18

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry to spark up an old thread, but this question and answer applied to me. I'm thinking about creating a php api for ajax calls. Would this be the best way to allow javascript to send methods as strings to interact with an object?
You can do it like that. You might also want to have a look at __call. I cannot tell you what's the best way though. It sounds like you want to do remote procedure calls (RPC). There are already some libraries for that, so you could also have a look at those.
something i actually like about php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.