Source Code:
(back to article)
<?php // Example 1 class Animal { protected $name; public function __construct($name) { $this->name = $name; } protected function getName() { return $this->name; } } class Dog extends Animal { public function bark() { $name = $this->getName(); echo "$name barks!" . PHP_EOL; } } $dog = new Dog("Rufus"); $dog->bark(); // Output: Rufus barks! // Example 2 class BankAccount { protected $balance = 0; public function deposit($amount) { $this->balance += $amount; } protected function canWithdraw($amount) { return $amount <= $this->balance; } } class SavingsAccount extends BankAccount { public function withdraw($amount) { if ($this->canWithdraw($amount)) { $this->balance -= $amount; echo "Withdrawal successful!" . PHP_EOL; } else { echo "Insufficient funds!" . PHP_EOL; } } } $savingsAccount = new SavingsAccount(); $savingsAccount->deposit(100); $savingsAccount->withdraw(50); // Output: Withdrawal successful! $savingsAccount->withdraw(100); // Output: Insufficient funds!
Result:
Report an issue