溫馨提示×

如何在PHP中正確使用parent

PHP
小樊
114
2024-07-31 15:12:08
欄目: 編程語言

在PHP中,可以使用parent關鍵字來調用父類中的方法或屬性。要正確使用parent關鍵字,需要按照以下步驟操作:

  1. 在子類中使用parent::來調用父類的方法。例如,如果要在子類中調用父類中的構造函數,可以使用以下語法:
class ParentClass {
    public function __construct() {
        echo 'Parent constructor called';
    }
}

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct();
        echo 'Child constructor called';
    }
}

$child = new ChildClass();
  1. 在子類中使用parent關鍵字來訪問父類中的屬性。例如,如果要在子類中獲取父類中的屬性值,可以使用以下語法:
class ParentClass {
    protected $name = 'Parent';
}

class ChildClass extends ParentClass {
    public function getName() {
        return parent::$name;
    }
}

$child = new ChildClass();
echo $child->getName(); // 輸出: Parent

通過正確使用parent關鍵字,可以方便地在子類中調用和訪問父類中的方法和屬性。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女