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相關知識,請造訪PHP中文網!
以上是php呼叫不同目錄的類別的詳細內容。更多資訊請關注PHP中文網其他相關文章!