HOWTO · PHP

PHP 中的建構函式

本文展示了 PHP 建構函式如何初始化在類中建立的物件的屬性。

在本教程中,我們將介紹 PHP 建構函式。我們將看到如何使用 __construct() 函式來初始化類中例項的屬性。

我們還將使用該函式來初始化類中具有給定引數的物件的屬性。

最後,我們將看到如何在子類中啟動物件並在兩個類都有單獨的建構函式時呼叫父類建構函式。

使用 PHP 建構函式初始化類中的物件的屬性

在下面的示例中,我們將建立一個類 Student 並使用 __construct 函式為 new Student 分配其屬性。

__construct 函式減少了與使用函式 set_name() 相關的程式碼數量。

<?php

class Student {
	// Define the attributes of your class
	
	public $name;
	public $email;
// Initialize the properties of the object you want to create in this class

function __construct($name, $email) {
	$this->name = $name;
	$this->email = $email;
}

function get_name() {
	return $this->name;
}

function get_email() {
	return $this->email;
}
}
$obj = new Student("John", "john567@gmail.com");
echo $obj->get_name();
echo "<br>";
echo $obj->get_email();
?>

輸出:

John
john567@gmail.com

使用 PHP 建構函式在類中初始化 Object with Parameters 的屬性

在下面的示例程式碼中,我們建立類 Military 並使用 __construct 函式來提供我們建立的物件的屬性和引數。

<?php
class Military {
	// Define the attributes of the class 'Military'
	
	public $name;
	public $rank;
	
	function __construct($name, $rank){
		$this->name = $name;
		$this->rank = $rank;
	}
	function show_detail() {
		echo $this->name." : ";
		echo "Your Rank is ".$this->rank."\n";
	}
}
$person_obj = new Military("Michael", "General");
$person_obj->show_detail();
echo "<br>";
$person2 = new Military("Fred", "Commander");
$person2->show_detail();
?>

輸出:

Michael : Your Rank is General
Fred : Your Rank is Commander

在 PHP 中在子類中啟動一個物件並在兩個類都有 Individual 建構函式時呼叫父類建構函式

<?php
class Student
{
	public $name;
	public function __construct($name)
	{
		$this->name = $name;
	}
}class Identity extends Student
{
	public $identity_id;
	
	public function __construct($name, $identity_id)
	{
		parent::__construct($name);
		$this->identity_id = $identity_id;
	}
	function show_detail() {
		echo $this->name." : ";
		echo "Your Id Number is ".$this->identity_id."\n";
	}
}
$obj = new Identity('Alice', '1036398');
echo $obj->show_detail();
?>

輸出:

Alice : Your Id Number is 1036398

Identity 類擴充套件了上述程式碼中的 Student 類。我們使用關鍵字 parent: 來呼叫 Student 類的建構函式。