【发布时间】:2016-02-19 10:40:12
【问题描述】:
我正在使用自动加载器通过名称空间加载类,它在 localhost 上运行良好,但在在线服务器上却不行。
当Autoloader.php 加载类时 PHP 向我显示此错误:
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的代码:
<?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';
}
}
类 EquipementsManager:
namespace backoffice\controllers;
use backoffice\entities\Connexion;
use backoffice\entities\Equipement;
class EquipementsManager{
//---some stuff to do----
}
我也试过这个__DIR__.'\\..\\'.$class . '.php' 仍然是同样的问题,在本地主机上工作但不能在线。
今天编辑(20/02/2016):
我将我的 autoload() 函数编辑为:
static function autoload($class){
$file = (strpos($class, 'backoffice') === false) ? $class : str_replace('\\', DIRECTORY_SEPARATOR, $class);
require $file . '.php';
}
现在我的文件已正确加载,但出现另一个错误:
require(JsonSerializable.php) [function.require]: failed to open stream: No such file or directory
我使用\JsonSerializable interface 将我的对象转换为 jason 数组,如下所示:
namespace backoffice\entities;
/**
* PropertyType
*/
class PropertyType implements \JsonSerializable
{
}
你知道这个接口在 SPL 中,为什么他不知道呢?!
【问题讨论】:
-
尝试更改文件的权限可能会起作用。 chmod 777 路径/to/file.php
-
发布你的
Autoloader.php的代码。 -
str_replace('\\', DIRECTORY_SEPARATOR, $class)。你的本地主机是 Win,服务器 nix*?
-
@Dmitry 抱歉还是不行!
-
我不明白为什么
'\\..\\'.$class . '.php'在你的本地主机上工作。这引用了服务器根文件夹中的一个文件,这很不寻常。你能发布你用来创建EquipementsManager对象的代码吗?
标签: php autoloader