Search⌘ K
AI Features

Chaining Methods and Properties

Explore how to use the $this keyword in PHP to access class properties and chain methods effectively. Understand creating fluent, readable code by returning the object within class methods and chaining actions like filling fuel and riding in a Car class.

We'll cover the following...

We can chain properties and methods to provide fluent code and improve its readability. When a class’s methods return the $this keyword, they can be chained together to create more streaming code.

How to chain methods and properties?

For example, 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 depends on the number of miles we’ve driven in our car and the amount of fuel that we put in the tank.

In order to ...