嗨,我现在学习PHP,我测试自动加载,但它不起作用。我有两个文件:start.php
和myClass.php
。我在路径./xampp/htdocs
中拥有的文件我想要如果我启动start.php使用自动加载包含myClass.php
和此功能。
这里是我的代码:
start.php
<?php
function _autoload($classname){
$filename = "./".$classname.".php";
include_once($filename);
}
$obj = new myClass();
?>
myClass.php
<?php
class myClass {
public function _construct(){
echo "Die Klasse wurde erfolgreich erzeugt";
}
}
?>
我收到此错误:
致命错误:第7行的D:\ Webserver \ xampp \ htdocs \ start.php中找不到类'myClass'
我犯了什么错。
答案 0 :(得分:2)
它是__autoload()
,而不是_autoload()
。前面有两个下划线。
_construct()
功能也是如此。
注意:PHP手册建议使用spl_autoload_register()
而不是__autoload()
函数,因为它允许更大的灵活性。此外,__autoload()
函数预计将来会被弃用。
答案 1 :(得分:1)
需要使用spl_autoload_register
- 将给定的功能注册为__autoload()
实施
function _autoload($class) {
$filename = $classname.".php"; //assumed, your class file and other files are in same directory
include_once($filename);
}
spl_autoload_register('_autoload');