问题
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
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:
namespace backoffice\controllers;
use backoffice\entities\Connexion;
use backoffice\entities\Equipement;
class EquipementsManager{
//---some stuff to do----
}
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
I use \JsonSerializable interface
to convert my objet to jason array, something like this:
namespace backoffice\entities;
/**
* PropertyType
*/
class PropertyType implements \JsonSerializable
{
}
as you know this Interface is in SPL so why he don't know it ?!
回答1:
try
$require = str_replace('\\', DIRECTORY_SEPARATOR, '..\\'.$class.'.php');
require($require);
来源:https://stackoverflow.com/questions/35503257/php-autoloader-cant-find-the-file