首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 類別繼承與方法覆寫實戰:從 People 到 Man 的完整示範

     編輯:PHP 相關知識

PHP 類別繼承與方法覆寫實戰:從 People 到 Man 的完整示範

父類別:People

<?php
// People.php
class People {
    protected $_age;
    protected $_name;
    protected $_gender;
    
    public function __construct($age, $name, $gender) {
        $this->_age = $age;
        $this->_name = $name;
        $this->_gender = $gender;
    }
    
    public function getName() {
        return $this->_name;
    }
    
    public function hi() {
        return $this->_name . ' say hi';
    }
}

子類別:Man 繼承 People

<?php
// Man.php
require_once 'People.php';

class Man extends People {
    public function __construct($age, $name) {
        // 呼叫父類別建構子,固定性別為 '男'
        parent::__construct($age, $name, '男');
    }
    
    // 方法覆寫:改寫 hi() 行為
    public function hi() {
        // 選項一:完全取代
        echo 'Man ' . $this->getName() . ' say hi';
        
        // 選項二:擴充父類別行為(取消註解)
        // echo parent::hi() . ' (from Man)';
    }
}

測試腳本

<?php
// index.php
require_once 'Man.php';

$m = new Man(10, 'Vito');
echo $m->hi(); 
// 輸出: Man Vito say hi

關鍵概念解析

概念關鍵字說明
繼承extends子類別取得父類別 public/protected 成員
建構子鏈parent::__construct()子類別需主動呼叫父建構子完成初始化
方法覆寫同名方法定義子類別方法取代父類別,可選擇呼叫 parent::method()
可見性protected允許子類別存取,禁止外部存取
多型型別提示 People $p傳入 Man 實例亦符合 People 型別要求

進階:final 防止覆寫

class People {
    // 禁止子類別覆寫
    final public function getSpecies() {
        return 'Human';
    }
}

class Man extends People {
    // 錯誤:Cannot override final method
    // public function getSpecies() { return 'Male Human'; }
}

介面與抽象類別擴充

interface Greetable {
    public function greet();
}

abstract class People implements Greetable {
    // 強制子類別實作
    abstract public function work();
    
    public function greet() {
        return "Hello, I'm {$this->_name}";
    }
}

class Man extends People {
    public function work() {
        return 'Working hard...';
    }
}

掌握繼承鏈、建構子責任鏈、覆寫策略與 final/abstract 約束,是 PHP 物件導向設計的核心基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved