I'm starting in POO
and SPL
and recently I faced the following problem: I have the following file that does all bootstrapping
of my application init.php
, and in it I do autoload
of all classes from the lib / directory:
set_include_path(get_include_path()
. PATH_SEPARATOR
. APP_ROOT_PATH
. DIRECTORY_SEPARATOR
. 'lib');
spl_autoload_extensions( ".php" );
spl_autoload_register();
However, it returns an error, always saying that some of the classes I instantiated later were not found:
/welcome.php - Uncaught Error: Class 'Hash' not found in /var/www/project/welcome.php:15
So, to debug, I made the following code:
spl_autoload_register(function($className){
$className = str_replace('\', DIRECTORY_SEPARATOR, $className);
$file = $className . ".php";
//echo 'Carregando arquivo ' . $file . PHP_EOL;
require_once $file;
});
And in this way, it works perfectly, all my classes are imported! Has anyone witnessed anything like this?
welcome.php
<?php
session_start();
define('APP_ROOT_PATH', dirname(__FILE__));
$configFiles = glob(APP_ROOT_PATH . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . '*.php');
foreach($configFiles as $configFile){
require_once $configFile;
}
set_include_path(get_include_path() . PATH_SEPARATOR . APP_ROOT_PATH . DIRECTORY_SEPARATOR . 'lib');
spl_autoload_extensions(".php");
//spl_autoload_register();
spl_autoload_register(function($className){
$otherClassName = $className;
$className = str_replace('\', DIRECTORY_SEPARATOR, $className);
$file = $className . ".php";
//echo 'Carregando arquivo ' . $file . ' ' . $otherClassName . PHP_EOL;
require_once $file;
});
//echo get_include_path();
require_once 'functions.php';
require_once 'vendor/autoload.php';