>  기사  >  백엔드 개발  >  PHP는 다른 디렉토리의 클래스를 호출합니다.

PHP는 다른 디렉토리의 클래스를 호출합니다.

angryTom
angryTom원래의
2019-10-29 14:42:552447검색

PHP는 다른 디렉토리의 클래스를 호출합니다.

php는 다른 디렉토리의 클래스를 호출합니다

1. 먼저 PHP는 다른 디렉터리에 있는 클래스의 상대 경로를 배열에 저장한 다음 루프를 사용하여 클래스

<?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);
}
}
});

2를 소개합니다. 개체를 만들고 호출하려면

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

Class 파일: 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>";
}
}

Class 파일: 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>";
}
}

PHP 관련 지식을 더 보려면 PHP中文网을 방문하세요!

위 내용은 PHP는 다른 디렉토리의 클래스를 호출합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.