php呼叫不同目錄的類

2020-07-16 10:06:47

php呼叫不同目錄的類

1、首先php把不同目錄的類的相對路徑存入陣列,然後使用迴圈引入類

<?php 
header('Content-type:text/html;charset=utf-8'); 
//spl_autoload_register()引數是匿名函數
spl_autoload_register(function($ClassName){
//將不同路徑的類檔案的路徑放入陣列中;
$arr = array(
"./$ClassName.class.php",
"./admin/controller/$ClassName.class.php"
);
// 迴圈不同路徑的類檔案的陣列
foreach ($arr as $filename) {
if (file_exists($filename)) {
require_once($filename);
}
}
});

2、使用new關鍵字建立物件並呼叫即可

$obj = new Student();
$obj->ShowInfo();
$obj2 = new Fruit();
$obj2->ShowInfo();

類檔案:命名為Student.class.php

<?php
header('Content-type:text/html;charset=utf-8'); 
final class Student{
const TILTLE = "3班";
private $name = "李立";
private $age = 20;
public function __construct(){
echo "{$this->name}的年齡是{$this->age}<br>";
}
public function ShowInfo(){
echo "{$this->name}的班級是".self::TILTLE."<br>";
}
}

類檔案:命名為Fruit.class.php

<?php
header('Content-type:text/html;charset=utf-8'); 
final class Fruit{
const TILTLE = "水果類";
private $name = "蘋果";
private $price = '20元/kg';
public function __construct(){
echo "{$this->name}的價格是{$this->price}<br>";
}
public function ShowInfo(){
echo "{$this->name}屬於".self::TILTLE."<br>";
}
}

以上就是php呼叫不同目錄的類的詳細內容,更多請關注TW511.COM其它相關文章!