The typical way to use :
<?php
class A {
public $var;
public function __construct($var){
$this->var = $var;
}
public function do_print(){
print $this->var;
}
}
?>
$obj = new A('Test');
$obj->do_print(); // Test
How can I implement something like:
$obj->var->method();
And why is this useful?
Your class could be something complicated, like a person that has an adress ( just like another class company could have one). Adress is a class in itself, so you'd want to call
or
You can implement this by making an object in your person (or company) class, just like a var:
By making
var
an object of another class, you can chain the method calls to one another.You can use this for neat things like Dependency Injection
Also, it may make your code bette readable and understandable because you don't have to buffer variables before making calls to their methods and can just call one method after the other.
Look at this example:
Which could be written like this using method chaining:
But, this is also harder to debug because if any of these methods throw an exception, you will just get the line number where the chain is, which can be quite a hazzle.
So, there are always two sides. It's just another style of programming.
Just be sure not to chain too long in a single line, as you will definitely lose overview.
BAD
GOOD