php calls classes in different directories
1. First, php puts classes in different directories relative to each other. Store the path in the array, and then use a loop to introduce the class
<?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. Use the new keyword to create an object and call it
$obj = new Student(); $obj->ShowInfo(); $obj2 = new Fruit(); $obj2->ShowInfo();
Class file: Name it 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>"; } }
Class file: Named 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>"; } }
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of php calls classes in different directories. For more information, please follow other related articles on the PHP Chinese website!