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.
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.
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).
$foo = 'bar';
$obj->$foo(); // calls the bar() method
You're looking at variable method calling.
$command
will be a string, the value of which is the name of a method in that class definition.