Home > Backend Development > PHP Problem > php calls classes in different directories

php calls classes in different directories

angryTom
Release: 2023-02-27 22:40:01
Original
2610 people have browsed it

php calls classes in different directories

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(&#39;Content-type:text/html;charset=utf-8&#39;); 
//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);
}
}
});
Copy after login

2. Use the new keyword to create an object and call it

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

Class file: Name it Student.class.php

<?php
header(&#39;Content-type:text/html;charset=utf-8&#39;); 
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>";
}
}
Copy after login

Class file: Named Fruit.class.php

<?php
header(&#39;Content-type:text/html;charset=utf-8&#39;); 
final class Fruit{
const TILTLE = "水果类";
private $name = "苹果";
private $price = &#39;20元/kg&#39;;
public function __construct(){
echo "{$this->name}的价格是{$this->price}<br>";
}
public function ShowInfo(){
echo "{$this->name}属于".self::TILTLE."<br>";
}
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template