问题描述
我正在使用自动加载器按名称空间加载类,它在localhost上运行良好,但在在线服务器上却无法运行.
当Autoloader.php
加载类时,PHP向我显示此错误:
I'm using autoloader to load classes by their namespaces, it's working fine on localhost but not on server online.
When Autoloader.php
loads classes PHP shows me this error :
Warning: require(\..\backoffice\controllers\EquipementsManager.php) failed to open stream: No such file or directory
但是我确定路径是正确的,并且文件EquipementsManager.php
在此路径中!这意味着自动加载器正在正确地使用正确的路径加载类,但是PHP一直在给我No such file or directory
错误!Autoloader.php
:
But I'm sure the path is correct and the file EquipementsManager.php
exists in this path !Which means the autoloader is loading classes properly with the right path but PHP keeps giving me No such file or directory
error !
Code of Autoloader.php
:
<?php
/**
* Class Autoloader
*/
class Autoloader{
/**
* Enregistre notre autoloader
*/
static function register(){
spl_autoload_register(array(__CLASS__, 'autoload'));
}
/**
* Inclue le fichier correspondant à notre classe
* @param $class string Le nom de la classe à charger
*/
static function autoload($class){
require '\\..\\'.$class . '.php';
}
}
Class EquipementsManager:
Class EquipementsManager:
namespace backoffice\controllers;
use backoffice\entities\Connexion;
use backoffice\entities\Equipement;
class EquipementsManager{
//---some stuff to do----
}
我也尝试过此__DIR__.'\\..\\'.$class . '.php'
仍然相同的问题,它可以在localhost上运行,但不能在线运行.
立即编辑(2016年2月20日):
我将autoload()函数编辑为:
I also tried this __DIR__.'\\..\\'.$class . '.php'
still the same problem, works on localhost but not online.
Edit today (20/02/2016):
I edited my autoload() function to this:
static function autoload($class){
$file = (strpos($class, 'backoffice') === false) ? $class : str_replace('\\', DIRECTORY_SEPARATOR, $class);
require $file . '.php';
}
现在我的文件已正确加载,但出现另一个错误:
Now my files are loaded correctly but another error appears :
require(JsonSerializable.php) [function.require]: failed to open stream: No such file or directory
我使用\JsonSerializable interface
将对象转换为jason数组,如下所示:
I use \JsonSerializable interface
to convert my objet to jason array, something like this:
namespace backoffice\entities;
/**
* PropertyType
*/
class PropertyType implements \JsonSerializable
{
}
您知道此接口位于SPL中,所以为什么他不知道它?!
as you know this Interface is in SPL so why he don't know it ?!
推荐答案
尝试
$require = str_replace('\\', DIRECTORY_SEPARATOR, '..\\'.$class.'.php');
require($require);
这篇关于PHP:自动加载器找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!