1
I am developing a project with the following structure:
The goal is to make autoload load the classes.
The archive autoload.php:
function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
spl_autoload_register('autoload');
Abstract class Person
namespace Projeto\Cliente;
use Projeto\Cliente\Interfaces\ClienteEnderecoInterface;
use Projeto\Cliente\Interfaces\ClienteImportanciaInterface;
abstract class Pessoa implements ClienteEnderecoInterface, ClienteImportanciaInterface{}
Interface Clienteenderecointerface
namespace Projeto\Cliente\Interfaces;
interface ClienteEnderecoInterface {}
Customer interface
namespace Projeto\Cliente\Interfaces;
interface ClienteImportanciaInterface {}
Classe Clientepf
namespace Projeto\Cliente\Tipos;
use Projeto\Cliente\Pessoa;
class ClientePF extends Pessoa{}
Classe Clientepj
namespace Projeto\Cliente\Tipos;
use Projeto\Cliente\Pessoa;
class ClientePJ extends Pessoa {}
Index.php
require_once('./inc/autoload.php');
$cli = new ClientePF();
$cli2 = new ClientePJ()
When trying to load the index, php the system informs that it cannot locate the classes:
( ! ) Warning: require(ClientePF.php): failed to open stream: No such file or directory in C:\wamp\www\inc\autoload.php on line 15 Call Stack # Time Memory Function Location 1 0.0010 152944 {main}( ) ...\index.php:0 2 0.0030 157944 spl_autoload_call ( ) ...\index.php:33 3 0.0030 158000 autoload( ) ...\index.php:33
What should be the correct way to declare namespaces and autoload? Full Code can be downloaded here: Github Given the success of psr-4, I can use it to replace psr-0
I think it would make your life easier to use Composer, even if you don’t install dependencies, it would automatically generate autoload for you.
– Wallace Maxters
And this Source Files folder, the Inc folder is inside it ?
– MagicHat
The idea is to do without Composer. To learn how to use namespaces
– Israel Zebulon
Everything is inside this Source Files folder. It’s already a Netbeans structure.
– Israel Zebulon
Just to learn, fine. But I encourage you to do through
PSR-4
, by the fact of the depreciation of Zero.– William Aparecido Brandino
If I were to use on PSR-4 as it would look?
– Israel Zebulon
From what I looked at in the code you are using the pattern closest to the PSR-4, you want to use namespace and underscore classes (for versions made for PHP 5.0 up to 5.2)?
– Guilherme Nascimento
I can do psr-4 then. the PHP I’m using is 5.4. I don’t need underscore.
– Israel Zebulon