I am doing an exercise on chaining and the mail method will not display when I chain the methods. Am I missing something here?
<?php
class User {
public $firstName;
public $lastName;
public function sayHello(){
echo 'Hello ' . $this->firstName . ' ' . $this->lastName;
return $this;
}
public function register(){
echo 'Registered ' . $this->firstName;
return $this;
}
public function mail(){
return 'Emailed';
}
}
$user1 = new User();
$user1->firstName = 'John';
$user1->lastName = 'Doe';
$user1->sayHello()->register()->mail();
?>
You are returning the value from the mail method, not echoing it. Try
var_dump($user1->sayHello()->register()->mail());
You are return
ing the text in mail()
.
You can either echo it when you call the methods:
echo $user1->sayHello()->register()->mail();
This way will let you save the results to a variable, for instance, to use later:
$result = $user1->sayHello()->register()->mail();
// do some work
echo "The result is: ".$result;
Or echo it in the method itself:
public function mail(){
echo 'Emailed';
}