It’s time to make our Pet class a little more interactive. We can make our pets walk and rest. Our pet can do a chain of events. Using chain methods makes running multiple methods at once cleaner and more efficient. Let’s learn how to use chain methods.
In our Pet class, add this bit of code.
public function WalkPet()
$this->energy -= 250;
echo $this->petName . ' is currently walking. Current Energy: ' . $this->energy . '<br>';
public function RestPet()
$this->energy += 100;
echo $this->petName . ' is currently resting. Current Energy: ' . $this->energy . '<br>';
We’re using a property named energy. Let’s create this property now in our class. Right under our other properties, add this line of code.
protected $energy = 2000;
We set our pet’s initial energy value to 2000. The WalkPet() method simply reduces this value by 250. We then echo out the current value of energy. Lastly, we return the object. I’ll explain in a moment why we do this. The RestPet() method is similar except it increases the value of energy by 100.
Using Chain Methods
Open up your index.php file and update your code to this.
$jack = new Pet( 'Jack' );
As you can see, instead of running each method line by line, you can run each method in 1 line just by using the object operator to tell PHP the sequence in which you want to run the methods. If you try viewing this file in a browser, you should see this.
Jack is currently walking. Current Energy: 1750
Jack is currently resting. Current Energy: 1850
Jack is currently walking. Current Energy: 1600
Jack was destroyed.
As I stated earlier, in order to use chain methods, you have to return the object. If you go back to your Pet class and remove the return lines, you’ll get this error.
Fatal error: Call to a member function RestPet() on a non-object
The RestPet() method is trying to run a method in WalkPet(), but WalkPet() is not an object. It’s just a method. So, in order to get around this, you simply return the object itself so RestPet() can run normally.
The downfall to running chain methods is that you must return the object. You may not return any other value as you’re only allowed to return 1 item. Chain methods can be useful for running multiple methods at once. If you would like more information about method chaining then go here.