OOP - Inheritance

🔹 ارث‌بری چیست؟

در OOP، ارث‌بری به این معنیه که یک کلاس فرزند (Child class) می‌تونه ویژگی‌ها (Properties) و متدهای (Methods) یک کلاس والد (Parent class) رو به ارث ببره.

با ارث‌بری:

  • می‌تونیم کدهای تکراری رو حذف کنیم.

  • می‌تونیم ویژگی‌ها و متدهای مشترک رو در یک کلاس والد تعریف کنیم.

  • می‌تونیم کلاس‌های تخصصی‌تر بسازیم که از یک کلاس کلی‌تر ارث‌بری می‌کنن.

🔹 تعریف ارث‌بری در PHP

برای تعریف ارث‌بری از کلمه‌ی کلیدی extends استفاده می‌کنیم:

class ChildClass extends ParentClass { // کدهای کلاس فرزند }

🔹 مثال ساده

<?php // کلاس والد class Vehicle { public $brand; public function setBrand($brand) { $this->brand = $brand; } public function getBrand() { return $this->brand; } } // کلاس فرزند class Car extends Vehicle { public function message() { return "This is a car and the brand is " . $this->brand; } } // ایجاد یک شیء از کلاس فرزند $myCar = new Car(); $myCar->setBrand("BMW"); echo $myCar->message(); ?>

📌 خروجی:

This is a car and the brand is BMW

🔹 دسترسی در ارث‌بری

  • اگر ویژگی یا متد در کلاس والد public یا protected باشه، در کلاس فرزند هم قابل دسترسیه.

  • اگر private باشه، کلاس فرزند نمی‌تونه بهش دسترسی داشته باشه.

🔹 بازنویسی متدها (Overriding)

کلاس فرزند می‌تونه متدی که در کلاس والد تعریف شده رو بازنویسی کنه:

<?php class Vehicle { public function intro() { return "This is a vehicle."; } } class Car extends Vehicle { public function intro() { return "This is a car."; } } $obj = new Car(); echo $obj->intro(); ?>

📌 خروجی:

This is a car.

🔹 استفاده از parent::

اگر بخوایم متد یا ویژگی والد رو صدا بزنیم، از parent:: استفاده می‌کنیم:

<?php class Vehicle { public function intro() { return "This is a vehicle."; } } class Car extends Vehicle { public function intro() { return parent::intro() . " But more specifically, this is a car."; } } $obj = new Car(); echo $obj->intro(); ?>

📌 خروجی:

This is a vehicle. But more specifically, this is a car.

✅ خلاصه

  • ارث‌بری با کلمه کلیدی extends تعریف می‌شه.

  • کلاس فرزند همه‌ی ویژگی‌ها و متدهای کلاس والد رو به ارث می‌بره (به جز private).

  • می‌تونیم متدها رو بازنویسی (Override) کنیم.

  • می‌تونیم با parent:: به متدها یا سازنده کلاس والد دسترسی داشته باشیم.