今日、名前空間とオートロードの使い方を学んでいますPHP
が、障害にぶつかったようです。spl_autoload_register
but 代わりにを使用しないとうまくいくようですrequire_once
。
私のフォルダ構造は最小限です:
- index.php
- class/
- Users.php
私のindex.php
ファイルには次のものがあります。
<?php
require_once('class/Users.php');
echo User::get(1);
私のclass/Users.php
ファイルには次のものがあります。
<?php
Class User {
function get($id) {
return $id;
}
}
これはまったく問題なく動作し、のIDを返します1
理想的には、オートロード機能を使用したいと思います。spl_autoload_*
これが私がやろうとしたことですが、成功しませんでした:
私のclass/Users.php
ファイルには次のものがあります。
<?php
namespace Users; // Added a namespace
Class User {
function get($id) {
return $id;
}
}
私のindex.php
ファイルには次のものがあります。
<?php
// Changed to using spl_autoload_register using an anonymous function to load the class
spl_autoload_register(function($class){
include('class/' . $class . '.php');
});
echo Users\User::get(1); // Added the Users namespace
しかし、私はエラーが発生します:
`Class 'Users\User' not found in /Applications/MAMP/htdocs/index.php on line 7`
何が間違っているのかよくわかりません。