Source Code:
(back to article)
<?php // Example 1 class Person { private $name; public function __construct($name) { $this->name = $name; } private function getName() { return $this->name; } public function greet() { $name = $this->getName(); echo "Hello, $name!" . PHP_EOL; } } $person = new Person("John"); $person->greet(); // Output: Hello, John! // Example 2 class BankAccount { private $balance = 0; public function deposit($amount) { $this->balance += $amount; } public function withdraw($amount) { if ($amount > $this->balance) { echo "Insufficient funds!" . PHP_EOL; } else { $this->balance -= $amount; echo "Withdrawal successful!" . PHP_EOL; } } } $account = new BankAccount(); $account->deposit(100); $account->withdraw(50); // Output: Withdrawal successful! $account->withdraw(100); // Output: Insufficient funds!
Result:
Report an issue