Menu
Forums
All threads
Latest threads
New posts
Trending threads
New posts
Search forums
Trending
What's new
New posts
New profile posts
Latest activity
Members
Current visitors
New profile posts
Search profile posts
Upgrades
Log in
Register
What's new
Search
Search
Search titles only
By:
All threads
Latest threads
New posts
Trending threads
New posts
Search forums
Menu
Log in
Register
Navigation
Install the app
Install
More options
Contact us
Close Menu
Forums
Software Development
Programming
Tutorials
[PHP] Method chaining
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
<blockquote data-quote="Markshall" data-source="post: 227524" data-attributes="member: 1872"><p>It seems method chaining has become more popular lately and a lot of people wonder how to do it, this simple tutorial will show you how.</p><p></p><p>[PHP]<?php</p><p>class Animal { //give the class a name</p><p> public function Dog() { //method</p><p> echo 'Woof';</p><p> return $this; //return Animal (this is basically what makes it chainable)</p><p> }</p><p> </p><p> public function Cat() {</p><p> echo 'Meow';</p><p> return $this;</p><p> }</p><p> </p><p> public function Sheep() {</p><p> echo 'Baa';</p><p> return $this;</p><p> }</p><p>}</p><p></p><p>$animal = new Animal();</p><p>$animal->Dog()->Cat()->Sheep();</p><p>?>[/PHP]</p><p></p><p>The outcome would then become:</p><p></p><p></p><p>You can also reuse the methods in a single chain, such as:</p><p>[PHP]$animal->Dog()->Cat()->Dog()->Dog()->Sheep();[/PHP]</p><p></p><p>Most people use this for eye-candy but it also makes code easier to read if coded properly.</p><p></p><p>Hope it helped,</p><p>Mark</p></blockquote><p></p>
[QUOTE="Markshall, post: 227524, member: 1872"] It seems method chaining has become more popular lately and a lot of people wonder how to do it, this simple tutorial will show you how. [PHP]<?php class Animal { //give the class a name public function Dog() { //method echo 'Woof'; return $this; //return Animal (this is basically what makes it chainable) } public function Cat() { echo 'Meow'; return $this; } public function Sheep() { echo 'Baa'; return $this; } } $animal = new Animal(); $animal->Dog()->Cat()->Sheep(); ?>[/PHP] The outcome would then become: You can also reuse the methods in a single chain, such as: [PHP]$animal->Dog()->Cat()->Dog()->Dog()->Sheep();[/PHP] Most people use this for eye-candy but it also makes code easier to read if coded properly. Hope it helped, Mark [/QUOTE]
Insert quotes…
Verification
Post reply
Forums
Software Development
Programming
Tutorials
[PHP] Method chaining
Top