PHP - وراثت و اصلاح کننده دسترسی محافظت شده(PHP - Inheritance and the Protected Access Modifier)
در فصل قبل آموختیم که ویژگیها یا روشهای محافظتشده میتوانند در داخل قابل دسترسی باشد کلاس و طبق کلاس های مشتق شده از آن کلاس. این به چه معناست؟
بیایید به یک مثال نگاه کنیم:
مثال
<?php class Fruit { public $name; public $color; public function __construct($name, $color) { $this->name = $name; $this->color = $color;
}
protected function intro() { echo "The fruit is {$this->name} and the color is {$this->color}.";
} }
class Strawberry extends Fruit { public function message() { echo "Am I a fruit or a berry? ";
} }
// Try to call all three methods from outside class $strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public $strawberry->message(); // OK. message() is public $strawberry->intro(); // ERROR. intro() is protected
?>
در مثال بالا می بینیم که اگر بخواهیم یک محافظت شده را فراخوانی کنیم متد (intro()) از خارج از کلاس، یک خطا دریافت خواهیم کرد. عمومی روش ها به خوبی کار خواهند کرد!
بیایید به مثال دیگری نگاه کنیم:
مثال
<?php class Fruit { public $name; public $color; public function __construct($name, $color) {
$this->name = $name; $this->color = $color;
} protected function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } }
class Strawberry extends Fruit { public function message() {
echo "Am I a fruit or a berry? "; // Call protected method from within derived class - OK $this -> intro(); } }
$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public $strawberry->message(); // OK. message() is public and it calls intro() (which is protected) from within the derived class ?>
در مثال بالا می بینیم که همه چیز خوب کار می کند! به این دلیل است که ما به محافظت شده متد (intro()) از داخل کلاس مشتق شده.