ارث بری در PHP

آموزش برنامه نویسی php

کلاس های فرزند تمامی ویژگی ها و متدهای از نوع public و protected را از کلاس والد ارث می برند. به علاوه، این کلاس ها می توانند ویژگی ها و متدهای مخصوص خود را نیز داشته باشند.

یک کلاس ارث برده شده توسط کلمه کلیدی extends تعریف می شود.

مثال:

<?php
class Fruit {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color; 
  }
  public function intro() {
    echo "The fruit is {$this->name} and the color is {$this->color}."; 
  }
}

// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
  public function message() {
    echo "Am I a fruit or a berry? "; 
  }
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?> 

در مثال فوق کلاس Strawberry از کلاس والد Fruit ارث می برد و می تواند از متدها و ویژگی های این کلاس که به صورت public تعریف شده اند، استفاده نماید.

بازنویسی متدهای ارث بری شده

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

<?php
class Fruit {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color; 
  }
  public function intro() {
    echo "The fruit is {$this->name} and the color is {$this->color}."; 
  }
}

class Strawberry extends Fruit {
  public $weight;
  public function __construct($name, $color, $weight) {
    $this->name = $name;
    $this->color = $color;
    $this->weight = $weight; 
  }
  public function intro() {
    echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight} gram."; 
  }
}

$strawberry = new Strawberry("Strawberry", "red", 50);
$strawberry->intro();
?> 

در مثال فوق، متدهای سازنده و intro با آنکه در کلاس والد تعریف شده بودند، در کلاس strawberry بازنویسی شدند.

استفاده از کلمه کلیدی final در هنگام تعریف کلاس و متد می تواند به ترتیب از ارث بری کلاس و بازنویسی متد جلوگیری نماید.

مثال:

<?php
class Fruit {
  final public function intro() {
    // some code
  }
}

class Strawberry extends Fruit {
  // will result in error
  public function intro() {
    // some code
  }
}
?> 

اجرای کد فوق، باعث بروز خطا خواهد شد. چون متد intro در کلاس والد به صورت final تعریف شده است.

استفاده متدها و ویژگی های استاتیک در ارث بری

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

مثال:

<?php
class domain {

public static $value = 1234;
  protected static function getWebsiteName() {
    return "samplewebsite.com";
  }
}

class domainWeb extends domain {
  public $websiteName;
  public $webValue;
  public function __construct() {
    $this->websiteName = parent::getWebsiteName();
   $this->webValue = parent::$value;
  } 
}

$domainWeb = new domainWeb;
echo $domainWeb -> webValue;
?> 

Related posts