php autoload 自动加载类和命名空间

php有个自动加载的函数叫__autoload,当找不到一个类包的时候,系统会执行这个函数

1.建立一个学生类文件Stu.class.php

<?php
//create by java-er.com  2020-02-10
class Stu{
	private $name;
	private $sex;
	function __construct($name,$sex){
		$this->name = $name;
		$this->sex = $sex;
	}
 
	function call(){
		echo "my name is ".$this->name;
		echo "<hr />I am a ".$this->sex;
	}
}
 
?>

2.建立一个测试文件 test.php

当系统找不到Stu类的时候,自动执行__autoload函数,帮我们require进来。

<?php
//create by java-er.com  2020-02-10 
 
function __autoload($class){
	require_once $class.'.class.php';
}
$stu = new Stu('Jack',"boy");
$stu->call();
 
?>

输出

my name is Jack
I am a boy

3.命名空间的处理
建立一个文件夹Lib Lib 下设置一个文件score

<?php
namespace Lib;
//create by java-er.com  2020-02-10
class Score{
	private $name;
	private $score;
	function __construct($name,$score){
		$this->name = $name;
		$this->score = $score;
	}
 
	function call(){
		echo "my name is ".$this->name;
		echo "<hr />My sports score is  ".$this->score;
	}
}
 
?>

修改test.php如下

<?php
//create by java-er.com  2020-02-10 
 
function __autoload($class){
	echo '['.$class.']<hr>';
	$class = str_replace("\\", "/", $class);
	require_once $class.'.class.php';
}
 
$stu = new Stu('Jack',"boy");
$stu->call();
 
echo '<hr />';
 
use Lib\Score;
$score = new Score('Tom','97');
$score->call();
?>

输出

[Stu]
my name is Jack
I am a boy
[Lib\Score]
my name is Tom
My sports score is 97


This entry was posted in PHP and tagged , , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/php-autoload-class/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*