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
  • 621
  • 1
  • 4
  • 12
Simon S.
  • 563
  • 4
  • 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
  • 11,056
  • 4
  • 42
  • 71
4
$foo = 'bar';
$obj->$foo(); // calls the bar() method

You're looking at variable method calling.

deceze
  • 510,633
  • 85
  • 743
  • 889
2

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

Scopey
  • 6,269
  • 1
  • 22
  • 34