温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php如何调用不同目录的类

发布时间:2020-10-14 14:29:33 来源:亿速云 阅读:138 作者:小新 栏目:编程语言

小编给大家分享一下php如何调用不同目录的类,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

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如何调用不同目录的类有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI