Chaining methods and properties

In the previous tutorial, we learned to use the $this keyword to approach properties and methods within the scope of the class. In this tutorial we will learn that, when a class’s methods return the $this keyword, they can be chained together to create much more streaming code.
For instance, in our Car class, let’s say that we want to measure how much fuel we have in our car’s tank. The amount of fuel in the tank is dependent upon the number of miles we have driven in our car, as well as the amount of fuel that we put in the tank.
In order to achieve our goal, we are going to put a public property $tank to our class that represents the number of gallons of fuel that we have in the car’s tank.

We must also add two methods to our Car class:
1. The fill() method adds gallons of fuel to our car’s tank.
2. The ride() method calculates how much fuel we consume when we ride a certain distance, and then subtracts it from the tank. In our example, we assume that the car consumes 1 gallon of fuel every 50 miles.

As we would like our code to look elegant, we will chain the methods and properties. Note the arrows in the code.

In words: How much fuel do we have left in our tank after putting in 10 gallons, and driving 40 miles?
In order to perform the chaining, the methods should return the $this keyword.
In order for us to be able to perform the chaining, the methods should return the object and, since we are inside the class, the methods should return the $this keyword. In the code below, we can see how each method returns the $this keyword in order to allow the chaining.

Now, we can create an object from the Car class with the name of $bmw and find out the number of gallons of fuel left in our car’s tank after we have filled the tank with 10 gallons of fuel and driven40 miles.

The number of gallons left in the tank: 9.2 gal.

Anuj Kumar

I'm Anuj kumar a web developer with 4+ year experience .I write blogs in my free time. I love to learn new technologies and share with others. I founded PHPGurukul in September 2015. The main aim of this website to is provide php , jquery , mysql , phpoops and other web development tutorials. I am trying best effort to make PHPGurukul useful for every single moment spend on this website. If you think this website is useful to visit please share with your friend and buddies.

Recommended Tutorials for you

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *