Search⌘ K

Solution Review: Chaining Methods and Properties

Explore how to implement method chaining in PHP using the $this keyword within class methods. Understand how to return the current object to enable chaining of multiple methods, demonstrated through a User class example with properties and methods like hello, register, and mail. This lesson helps you write more fluent and readable object-oriented PHP code.

We'll cover the following...

Solution

PHP
<?php
class User {
public $firstName;
public function hello() {
echo "hello, " . $this -> firstName;
return $this;
}
public function register() {
echo " >> registered";
return $this;
}
public function mail() {
echo " >> email sent";
}
}
function test()
{
$user1 = new User();
$user1 -> firstName = "Jane";
$user1 -> hello() -> register() -> mail();
}
test();
?>

Explanation

  • Line 2: We write the User class with $firstName as a public property.
  • Line 5: We write the hello() method that says hello to the user. We return $this
...