23 June 2010 ~ 1 Comment

PHP5 Method Chaining

One improvement over PHP4 to PHP5 is something called method chaining and enables us to do pretty cool things like:

// PHP 5
$dog->breed('Min Pin')->color('Black');

Skooter WinnThis post was powered by Skooter ($dog->breed(‘Min Pin’)->color(‘Black’);)

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.

To be able to chain methods together, 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. Let’s put all of this into action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Dog {
     var $dog_color;
     var $dog_breed;
 
     function breed($val){
          $this->dog_breed = $val;
     }
 
     function color($val){
          $this->dog_color = $val;
     }
 
     function seedog(){
          echo "Breed: " . $this->dog_breed . " Color: " . $this->dog_color;
     }
}

Now, we can create a new Dog and give them a breed and color. Using the seedog method.

// PHP 4 (OLD STYLE)
$dog = new Dog();
$dog->breed('Min Pin');
$dog->color('Black');
$dog->seedog();
// Will echo = Breed: Min Pin Color: Black

Implementing Method Chaining

We will be using the same class from above but adding two lines to it like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog {
     var $dog_color;
     var $dog_breed;
 
     function breed($val){
          $this->dog_breed = $val;
          return $this; // <- Returning the object
     }
 
     function color($val){
          $this->dog_color = $val;
          return $this; // <- Returning the object
     }
 
     function seedog(){
          echo "Breed: " . $this->dog_breed . " Color: " . $this->dog_color;
     }
}

Using the class above we can now use method chaining!

// PHP 5
$dog = new Dog();
$dog->breed('Min Pin')->color('Black')->seedog();
// Will echo = Breed: Min Pin Color: Black

It will give you the same result but your code is much cleaner and easier to read.

Tags:

One Response to “PHP5 Method Chaining”

  1. Gwen 28 June 2010 at 6:15 pm Permalink

    thank you for this, i used this to help show some new dev how to use method chaining.