PHP 中的自動載入類

John Wachira 2022年5月13日
PHP 中的自動載入類

在本教程中,我們將介紹 spl_autoload_register() 函式。我們將看到如何載入未在 PHP 指令碼中定義的類。

在 PHP 中使用 spl_autoload_register() 函式自動載入類

首先,我們將建立一個 PHP 類。我們將呼叫這個類 fruit 並將 PHP 指令碼儲存在我們本地伺服器文件根目錄中的資料夾 fruits 中。

我們還將在類中建立物件 apple

將 PHP 指令碼檔案命名為類名很重要。在我們的例子中,我們將把我們的 PHP 指令碼命名為 fruit.php

<?php
// Creating a Fruit class

Class fruit {
	public $name;
	public $color;
	
	public function set_name($name) {
		$this->name = $name;
	}
	public function get_name() {
	return $this->name;
	}
}
$apple = new fruit();
$apple->set_name('Apple');

echo $apple->get_name();
?>

輸出:

Apple

讓我們在新指令碼的此類中建立一個物件。我們將使用 spl_autoload_register() 函式在我們的新 PHP 指令碼上例項化類並建立 Orange

下面的程式碼說明了如何建立自定義自動載入函式,在我們的例子中是 autoload fruits()。在使用 spl_autoload_register() 函式時,我們將參考我們的自定義自動載入函式。

<?php
//Define the autoload function
function autoloadFruit($className) {
	$filename = 'fruits' . $class. '.php.';
	if(is_readable($filename)){
		require $filename;
	}
}
// Using the spl_autoload_register() Function to Autoload Class Fruit using the autoload function above.

spl_autoload_register('autoloadFruit');
class autoloadFruit
{
	public function set_name($name) {
		$this->name = $name;
	}
	public function get_name() {
	return $this->name;
	}
}
$orange = new autoloadfruit();
$orange->set_name('Orange');

echo $orange->get_name();
?>

輸出:

Orange

當你有許多指令碼要參考時,你可以新增多個自動載入功能。你只需要為每個類建立一個自定義的自動載入功能。

或者,你可以使用 include_once() 函式。

作者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn