Page 332 - Computer Software Application TP - Volume 1
P. 332
COMPUTER SOFTWARE APPLICATION - CITS
// Parent class
class Animal
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function speak()
{
echo $this->name . “ makes a sound.\n”;
}
}
// Child class inheriting from Animal
class Dog extends Animal
{
public function bark()
{
echo $this->name . “ barks.\n”;
}
}
// Child class inheriting from Animal
class Cat extends Animal
{
public function meow()
{
echo $this->name . “ meows.\n”;
}
}
// Creating instances of child classes
$dog = new Dog(“Buddy”);
$cat = new Cat(“Whiskers”);
// Calling methods from parent and child classes
$dog->speak(); // Output: Buddy makes a sound.
$dog->bark(); // Output: Buddy barks.
$cat->speak(); // Output: Whiskers makes a sound.
$cat->meow(); // Output: Whiskers meows.
?>
</body>
317
CITS : IT & ITES - Computer Software Application - Exercise 60 CITS : IT & ITES - Computer Software Application - Exercise 60