4

I am trying to understand this line of code:

$ret = $box->$command();

The method command is not defined in the class $box, and it is strange that there is a $ before command. I just don't get it.

Guru
  • 633
  • 1
  • 4
  • 12
Simon S.
  • 513
  • 3
  • 21

3 Answers3

4

This executes the method with the name stored in the $command variable on the object stored in$box.

So, supposing the class of $box has a method called foo, then this would work:

$command = "foo";
$box->$command();

and would be equivalent to

$box->foo();

only that the former way is more flexible, as it allows you to dynamically call a function depending on the value of a variable. Beware to check the possible values of $command however, do take care that it isn't filled by user input somehow (that might allow malicious people to do unexpected things with the php code).

codeling
  • 10,672
  • 4
  • 37
  • 67
4
$foo = 'bar';
$obj->$foo(); // calls the bar() method

You're looking at variable method calling.

deceze
  • 491,798
  • 79
  • 706
  • 853
2

$command will be a string, the value of which is the name of a method in that class definition.

Scopey
  • 6,210
  • 1
  • 21
  • 34