I understand that $something->function(); is calling a function within a class but what does $something->somethingelse->function(); mean?
3 Answers
I assume you mean $something->somethingelse->function().
It means that a property of $something named $somethingelse is another object that has the method function().
$something = new Class1();
$something->somethingelse = new Class2(); // Class2 has the "function()" method
// Now I can call...
$something->somethingelse->function();
4 Comments
you can say it like this:
class foo {
public $bar;
}
class bar {
public $baz;
}
class baz {
function blip() { echo "Hello World"; }
}
$foo = new foo();
$foo->bar = new bar(); // setting bar to new object
$foo->bar->baz = new baz(); // setting baz to new object
$foo->bar->baz->blip(); // calling the blip function
1 Comment
The class of the instance $something contains an instance variable called $somethingelse which is also an object (instance of a class).
It's considered a bad practice (see Law of Demeter on Wikipedia).
A nice explanation of the Law of Demeter is on c2.com of Peter Van Rooijen is:
You can play with yourself.
You can play with your own toys (but you can't take them apart),
You can play with toys that were given to you.
And you can play with toys you've made yourself.
That is in plain English:
Your method can call other methods in its class directly
Your method can call methods on its own fields directly (but not on the fields' fields)
When your method takes parameters, your method can call methods on those parameters directly.
When your method creates local objects, that method can call methods on the local objects.
BUT
One should not call methods on a global object
One should not have a chain of messages a.getB().getC().doSomething() in some class other than a's class.
Another interesting read is Law of Demeter Revisited for a less strict approach.
$something->$somethingelse->function();and not$something->somethingelse->function();or$something->somethingelse()->function();?