Docs/PHP/OOP Basics

PHP OOP

Konsep

  • Class — blueprint
  • Object — instance dari class
  • Properties — variabel dalam class
  • Methods — fungsi dalam class
  • Inheritance — extends
  • Visibility — public, protected, private
  • Constructor — __construct()
index.php
Try It →
<?php
class Character {
    public function __construct(
        public string $name,
        protected int $level = 1,
        private int $xp = 0
    ) {}
    
    public function gainXP(int $amount): void {
        $this->xp += $amount;
        if ($this->xp >= 100) {
            $this->level++;
            $this->xp -= 100;
            echo "🎉 {$this->name} leveled up to {$this->level}!
";
        }
    }
    
    public function getInfo(): string {
        return "{$this->name} | Lv.{$this->level} | XP:{$this->xp}/100";
    }
}

class Warrior extends Character {
    public function attack(): string {
        return "⚔️ {$this->name} attacks!";
    }
}

$hero = new Warrior("Arya", 3);
echo $hero->getInfo() . "
";
echo $hero->attack() . "
";
$hero->gainXP(120);
echo $hero->getInfo();
?>