TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
Advertisement
Associates
Associates
techtuts Darkmindz
CSS Tutorials Tutorialsphere.com - Free Online Tutorials
Boston PHP SurfnLearn
Reply
 
LinkBack (3) Thread Tools Search this Thread Display Modes
Old 09-18-2007, 02:14 PM   3 links from elsewhere to this Post. Click to view. #1 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 754
Thanks: 2
Salathe is on a distinguished road
Default PHP5 Method Chaining

Introduction
In this article, I'll be talking about a useful new feature introduced in PHP5 as part of the OOP improvements over PHP4. This feature is called Method Chaining and enables us to do pretty cool things like:
PHP Code:
$object->method_a()->method_b()->method_c(); 
So really what's this all about? Well, one change (of many) between PHP4 and PHP5 is that now methods can return objects. That's only a small change but allows for a new way of thinking about how you handle objects and their methods.

In order to be able to chain methods together, as mentioned earlier, you need to be able to return an object. The returned object does not necessarily need be the same one from which the method is being called, but we'll not be touching on that fact in this article. Let's go for a quick illustration of how to put all of this into action.

Regular Use of a Class
We'll start off with a basic class, which doesn't do anything particularly interesting but it will serve our purpose.

PHP Code:
// This Person class encapsulates a couple of properties which
// a person might have: their name and age.
// We also give the Person the opportunity to introduce themselves.
class Person
{
    private 
$m_szName;
    private 
$m_iAge;
    
    public function 
setName($szName)
    {
        
$this->m_szName $szName;
    }
    
    public function 
setAge($iAge)
    {
        
$this->m_iAge $iAge;
    }
    
    public function 
introduce()
    {
        
printf(
            
'Hello my name is %s and I am %d years old.',
            
$this->m_szName,
            
$this->m_iAge);
    }

Now, we can create a new Person (see example below) and give them a name and age. Using the introduce method, the person can them introduce themselves.

PHP Code:
// We'll be creating me, digitally.
$peter = new Person();

// Let's set some attributes and let me introduce myself.
$peter->setName('Peter');
$peter->setAge(23);
$peter->introduce(); 
The above example would output:
Hello my name is Peter and I am 23 years old.

Implementing Method Chaining
Great, but you already knew how to do that didn't you! In actuality, we only need to add two lines of code to the basic class above to enable us to write a chain, and the second line is a repeat of the first! How's it done? Quite simply we need to return the Person object from each method. At the moment, none of the methods actually return anything so we'll amend that now. We just need to add return $this; to the methods setName and setAge.

The amended Person class is as follows:
PHP Code:
// This Person class encapsulates a couple of properties which
// a person might have: their name and age.
// We also give the Person the opportunity to introduce themselves.
class Person
{
    private 
$m_szName;
    private 
$m_iAge;
    
    public function 
setName($szName)
    {
        
$this->m_szName $szName;
        return 
$this// We now return $this (the Person)
    
}
    
    public function 
setAge($iAge)
    {
        
$this->m_iAge $iAge;
        return 
$this// Again, return our Person
    
}
    
    public function 
introduce()
    {
        
printf(
            
'Hello my name is %s and I am %d years old.',
            
$this->m_szName,
            
$this->m_iAge);
    }

Ok, is that it? Yep, really. Because we return the Person from those methods, it enables us to group method calls together in a sequence, or chain. I'll re-do the previous example but this time using our new magical chaining abilities.

PHP Code:
// We'll be creating me, digitally.
$peter = new Person();

// Let's set some attributes and let me introduce myself, 
// all in one line of code.
$peter->setName('Peter')->setAge(23)->introduce(); 
That example will produce exactly the same output as our regular, boring example earlier! All because we return the Person object in the setName/Age methods.

How does that work?
If you're a bit confused about precisely what is going on here, let me try to walk you through the process, step by step. We'll go through the line of code as it is processed, from left to right.

First up is $peter->setName('Peter'). This assigns the person's name to be Peter, my name and returns $this -- that is, the $peter object. So at the moment Peter has his name, but no age!

Next up comes ->setAge(23). Because we're chained with the previous method, PHP interprets the code and says "execute the setAge method belonging to whatever was returned from the previous method." In this case, PHP executes the setAge method belonging to our Person object, $peter.

The exact same thing happens when we finally call the introduce method. PHP executes the introduce method belonging to whatever was returned from the setAge method call: $peter.

Hopefully, that's at least a bit clear and I'll let you mull over this confusing (until you get it) subject for a while. I'll leave you with the note that because we can chain methods, they can be called more than once and in whatever order we like which could lead to the amazingly useless snippet below:
PHP Code:
// Hello my name is Winifred and I am 72 years old.
$peter->setAge(23)
      ->
setName('Peter')
      ->
setName('Winifred')
      ->
setAge(72)
      ->
introduce(); 
In Conclusion
We can boil this whole article down into one short sentence. If you return $this then you can chain the method calls together. Done. :)
__________________

Last edited by Salathe : 09-19-2007 at 09:33 PM.
Salathe is offline  
Reply With Quote
The Following 5 Users Say Thank You to Salathe For This Useful Post:
Andrew (01-01-2008), codefreek (10-28-2008), gilbertoalbino (10-28-2008), Runar (11-12-2008), zxt3st (11-28-2008)
Old 10-01-2007, 12:06 PM   #2 (permalink)
The Gregarious
Upcoming Programmer Inquisitive 
 
Join Date: Sep 2007
Posts: 748
Thanks: 85
Tanax is on a distinguished road
Default

And this would be useful because..? :P
Tanax is offline  
Reply With Quote
Old 10-01-2007, 12:24 PM   #3 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 438
Thanks: 22
Karl is on a distinguished road
Default

Readability and reduction of code repeation. Consider the following example I use in my library:

PHP Code:
$aMembers $this->m_pMembers
                    
->join('jobs')
                    ->
join('orders')
                    ->
fetchAll($szFields$szConditions); 
The same code could be written like this, without method chaining:

PHP Code:
$this->m_pMembers->join('jobs');
$this->m_pMembers->join('orders');
$aMembers $this->m_pMembers->fetchAll($szFields$szConditions); 
Admitidly, we've actually added an extra line of code using method chiaining, but we've reduced the amount of code written, removed duplicate code and made it much easier to read. It's all a matter of preference in all honesty, there is no clear cut advantage (that I personally know of, can anyone give me one?) of using method chaining, it's simply a OOP feature that can be used to help improve your code.
Karl is offline  
Reply With Quote
The Following 2 Users Say Thank You to Karl For This Useful Post:
codefreek (10-28-2008), Runar (11-12-2008)
Old 10-23-2007, 12:25 PM   #4 (permalink)
The Wanderer
 
Acrylic's Avatar
 
Join Date: Sep 2007
Location: Rochester, NY
Posts: 6
Thanks: 1
Acrylic is on a distinguished road
Default

Wow! Thanks for this it will come in handy. :)
Acrylic is offline  
Reply With Quote
Old 11-13-2007, 06:56 PM   #5 (permalink)
The Contributor
 
Join Date: Nov 2007
Location: California
Posts: 56
Thanks: 0
dschreck is on a distinguished road
Default good tutorial

good write up, needed to explain this to some JR's, googled it, and found this here. Good job explaining this very usable and convenient pattern.

so, kudos for you.
dschreck is offline  
Reply With Quote
Old 11-15-2007, 12:13 PM   #6 (permalink)
The Contributor
 
Join Date: Nov 2007
Posts: 32
Thanks: 5
Morishani is on a distinguished road
Default

Thanks! Very useful :)
Send a message via ICQ to Morishani Send a message via MSN to Morishani
Morishani is offline  
Reply With Quote
Old 10-28-2008, 03:55 PM   #7 (permalink)
The Visitor
 
gilbertoalbino's Avatar
 
Join Date: Oct 2008
Location: Brazil, Balneário Camboriu
Posts: 4
Thanks: 1
gilbertoalbino is on a distinguished road
Default

Hum, pretty good! I was just thinking about it and found that this is very great a progress to PHP language, because, as you must know most languages, both scripting or not have method chaining somehow, to webdevelopers it would be pretty nice for PHP allow method chaining, in fact we generally deal with Javascript often, and as you know too, string.value.length is now possible in php as string()->value()->length().
Great post, thanks again!
Send a message via MSN to gilbertoalbino
gilbertoalbino is offline  
Reply With Quote
Old 11-28-2008, 02:07 AM   #8 (permalink)
The Visitor
 
Join Date: Nov 2008
Posts: 3
Thanks: 0
exquisiteoath is on a distinguished road
Default Doh!

I've been writing chaining in JavaScript with exactly this same approach for close to a year new, wishing that PHP could offer the same functionality.

Then it occurs to me... hey, I never googled it. I google it, and this is the first thing I find.

I had completely missed that we can now return objects. That changes everything.
exquisiteoath is offline  
Reply With Quote
Old 11-28-2008, 02:25 AM   #9 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,641
Thanks: 72
Wildhoney is on a distinguished road
Default

Lol Such a good find, I imagine! Welcome to the community as well, my friend!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 11-28-2008, 05:17 AM   #10 (permalink)
The Acquainted
 
zxt3st's Avatar
 
Join Date: Apr 2008
Posts: 145
Thanks: 13
zxt3st is on a distinguished road
Default

well, as i study some of the articles regarding classes, i have read about this technique wherein you return the object so that you can do the chain.

e.g
the object is the cat then we apply some color on it. Yellow after which return the object again, so we can again apply any other property on it.

Cat(object)->yellow(color)->Cat(returned object)->etc..

so any instances if we apply it to classes we can do the chain as what discuss above.(if im not mistaken about it)

PHP Code:
$obj = new object();
$obj->setname(params)->setcolor(params)->setsize(params)->etc.. 
Thanks for the share, atleast we also have a detail discussion about it too :)
zxt3st is offline  
Reply With Quote
Old 11-28-2008, 12:38 PM   #11 (permalink)
The Visitor
 
gilbertoalbino's Avatar
 
Join Date: Oct 2008
Location: Brazil, Balneário Camboriu
Posts: 4
Thanks: 1
gilbertoalbino is on a distinguished road
Default

Quote:
Originally Posted by exquisiteoath View Post
I've been writing chaining in JavaScript....
Sure! This is fantastic!
__________________
...it's about producing and sharing!
Send a message via MSN to gilbertoalbino
gilbertoalbino is offline  
Reply With Quote
Reply


LinkBacks (?)
LinkBack to this Thread: http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
Posted By For Type Date
Quick Web Source - advanced php - php5's oop method chaining This thread Refback 01-15-2008 12:13 AM
OOP PHP - php-brasil | Grupos do Google This thread Refback 12-27-2007 11:09 AM
OOP PHP - php-brasil | Grupos do Google This thread Refback 12-24-2007 10:36 AM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 04:49 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0