Chaining method calls together
-
13-07-2021 - |
Pergunta
For example record like this: property3->property2->property1
is understood for me, this means that property of class, is object of another class, for example:
class a {
public $property1 = "some";
}
class b {
function __construct () {
$this->property2 = new a();
}
}
$obj = new b();
echo $obj->property2->property1;
this understood. but I can not understood records like this: method1()->method2()->method3()
can you post simple example, who using these records?
Solução
A simple example :
class A {
function fooA() {
echo "a...";
return $this;
}
function fooB() {
echo "b...";
return $this;
}
function fooC() {
echo "c...";
}
}
$a = new A();
$a->fooA()->fooB()->fooC();
Or with several classes :
class A
{
private $b;
public function __construct()
{
$this->b = new B();
}
public function fooA()
{
echo "A...";
return $this->b;
}
}
class B
{
public function fooB()
{
echo "B...";
}
}
$a = new A();
$a->fooA()->fooB();
Outras dicas
It means that these functions return objects. For example, the following is possible (assuming $pdo is a valid PDO object):
$result = $pdo->query("SELECT * FROM `table`")->fetchAll();
This may not always be favorable, because you:
- Lose readabiliy.
- Lose the ability to use the objects in between.
Lose the ability to check for errors, and you are counting on the methods to return what you think it is.
In this example, you only get the resultset in the form of an
array
, but you cannot accessPDOStatement
which is returned byPDO::query()
. In this case, it may not matter, in some cases it might.Also,
PDO::query()
may return a BOOLEANfalse
in the case of an error, which would give an unexplained "MethodfetchAll()
used on an non-object" error.