View Subcategory
Define a class
Declare a class named Greeter that takes a string on creation and greets using this string if you call the
"greet" method.
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.";
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.";
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
erlang
Greeter = make_greeter("world!"),
Greeter(greet).
Greeter(greet).
Instantiate object with mutable state
Reimplement the Greeter class so that the
For example, if the greetee is changed to
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".
For example, if the greetee is changed to
'Tommy' using the setter, the 'greet' method would display:
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.\n";
}
public function getWhom() {
return $this->whom;
}
public function setWhom($whom) {
$this->whom = $whom;
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
$g->setWhom("Jean-Jaques");
$g->greet();
echo "I have just greeted " . $g->getWhom() . ".\n";
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.\n";
}
public function getWhom() {
return $this->whom;
}
public function setWhom($whom) {
$this->whom = $whom;
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
$g->setWhom("Jean-Jaques");
$g->greet();
echo "I have just greeted " . $g->getWhom() . ".\n";
