[php-src] Issue #10685: spl_autoload_register must include a class map for interfaces and traits
| From: | jerryurenaa | Date: | Thu, 23 Feb 2023 17:30:55 +0000 |
| Subject: | [php-src] Issue #10685: spl_autoload_register must include a class map for interfaces and traits | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-243795@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/10685
Author: jerryurenaa
### Description
How would you load an interface class or trait class that is contained inside a different file name?
Is this a bug? is there any sort of class mapping in PHP? What if we do not want to use composer?
consider this example.
filenames = Notworking.php, OtherFile.php
```php
<?php
namespace Example;
interface ICrypto { }
class Crypto implements ICrypto
{
private IotherFileInterface $test = new OtherFileClass();
}
```
Resulted in this output:
```
spl_autoload_register should have a way to know if that class is inside another file or not.
It would be very easy if we could use reflection before including but as you all know we must
include the file before the reflection class making it an impossible solution in this case.
```
But I expected this output instead:
```
spl_autoload_register should include all classes inside a file. Or php should have a mapping
function.
```
This is the only way that I found to fix my issue. Please consider implementing some sort of class
map within the autoload.
```php
<?php
$loaded = [
"Services\\Auth\\IAuthService" =>
"/var/www/html/src/Services/Auth/AuthService.php",
"Repositories\Auth\IAuthRepository" =>
"/var/www/html/src/Repositories/Auth/AuthRepository.php",
"Core\Database\Mysql\IMysql" =>
"/var/www/html/src/Core/Database/Mysql/Mysql.php",
];
spl_autoload_register(function($className) use (&$loaded) {
//possible directories
$dirs = array(
dirname(__DIR__) . '\\src\\',
dirname(__DIR__) . '\\',
);
foreach( $dirs as $dir )
{
$path = $dir. $className .'.php';
$path = str_replace("\\", "/", $path);
if (file_exists($path))
{
require_once($path);
return;
}
else if(array_key_exists($className, $loaded))
{
require_once($loaded[$className]);
return;
}
else
{
die($className . " Not mapped");
}
}
});
```
### PHP Version
PHP 8.2.1
### Operating System
_No response_