how can i do additional method(such as Laravel), that extends previous in chaining ?
For example:
$page->loadFooter()->withExtension("script_name")
where withExtension()
is additional method, that affect result of loadFooter()
method ?
Asked
Active
Viewed 97 times
0

Jozef Cipa
- 2,133
- 3
- 15
- 29
3 Answers
1
The way method chaining works is that each call has to return the object itself (i.e. $this
).
So your page class definition would look like:
class Page {
public function loadFooter() {
/* ... */
return $this;
}
public function withExtension($script) {
/* ... */
return $this;
}
}
What's actually happening in method chaining is that the next function gets called on the returned object.

samlev
- 5,852
- 1
- 26
- 38
0
loadFooter()
just needs to return an object that has a withExtension
method. So if you want to affect the $page
object than loadFooter
should return its object.
/*Within $page's class*/
public function loadFooter(){
/**insert Code**/
return $this;
}

Dan
- 10,614
- 5
- 24
- 35
0
In your function you return an object, typically $this
class Page {
public $footer;
public function loadFooter() {
$this->footer = file_get_contents("footer.html");
return $this;
}
public function withExtension($script) {
$this->footer = str_replace($this->footer, "</body>", "<script src='{$script}'></script></body>");
}
}
$page = new Page();
$page->loadFooter()->withExtension("script name");

dave
- 62,300
- 5
- 72
- 93
-
Thanks, but it has little problem. When I load footer with extension method it will looks like : `... – Jozef Cipa Oct 27 '15 at 17:38
-
See the edit, this will put the script right before the closing body tag – dave Oct 27 '15 at 17:49