Hi! Could we please enable some services and cookies to improve your experience and our website?

SQLize | PHPize | SQLtest

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

A A A
Login    Share code      Blog   FAQ
Copy Format Clear
<?php abstract class Character { protected $name; protected $health = 100; private static $maxHealth = 100; public function __construct($name) { $this->name = $name; } // Abstract: all characters MUST define this abstract public function attack(); // Public method: can be called from anywhere public function heal() { $this->health += 10; if ($this->health > self::$maxHealth) { $this->health = self::$maxHealth; } echo "$this->name heals! Health is now $this->health\n"; } // Protected static: can be used in children, but not outside protected static function getMaxHealth() { return self::$maxHealth; } // Private method: only this class can use it private function secretPower() { return "Hidden Force!"; } public function revealSecret() { // This is okay: private method used from inside same class return $this->secretPower(); } } class Player extends Character { public function attack() { return "$this->name attacks with sword!"; } public function showMaxHealth() { // OK: calling protected static method from parent return "Max health is: " . self::getMaxHealth(); } } class Enemy extends Character { public function attack() { return "$this->name attacks with claws!"; } } // Test it out: $player = new Player("Hero"); echo $player->attack() . "\n"; // Hero attacks with sword! echo $player->showMaxHealth() . "\n"; // Max health is: 100 $player->heal(); // Hero heals! Health is now 110 -> capped at 100 echo $player->revealSecret() . "\n"; // Hidden Force! $enemy = new Enemy("Goblin"); echo $enemy->attack() . "\n"; // Goblin attacks with claws! // Invalid use cases (will error if uncommented): // echo $player->secretPower(); ❌ private // echo Character::getMaxHealth(); ❌ protected

Stuck with a problem? Got Error? Ask AI support!

Copy Clear