If you no longer want to have problems with this type of situation I recommend using an AutoLoader ready. My tip is to use AutoLoader from Composer , for this you have to install the same.
Installing Composer
To install Composer simply run a command line, nothing else! There are other ways to install Composer, but I'll show you the one I like the most.
Run the following command at the root of your project:
$ curl -sS https://getcomposer.org/installer | php
Or
php -r "readfile('https://getcomposer.org/installer');" | php
Remembering that if you use the second option you have to run PHP to do so put his folder in environment variables or pass his path at the time of executing the command.
Ready now you have Composer installed in your project! Now we just need to ask him to install the dependencies on his project and when installing the dependencies he will install an AutoLoader automatically.
Installing dependencies
First you have to have the Composer configuration file. At the root of your project create the following file:
composer.json
{
"name": "fabio/autoload",
"description": "Ensinando Autoload",
"type": "project",
"license": "MIT",
"authors": [
{
"name": "Fábio Lemos Elizandro",
"email": "[email protected]"
}
],
"autoload": {
"psr-0": {
"": ""
}
},
"require": {}
}
Please note that I did not declare any dependency because I am only interested in AutoLoader. After creating this file run the following command at the root of your project:
$ php composer.phar install
Or
$ php composer.phar update
This will depend on your intent.
Alternative configuration
You can configure the AutoLoader of your project, a configuration that I use is as follows:
"autoload": {
"psr-0": {
"": "src/"
}
},
Now I can leave my source codes inside the directory without needing to include the same in the namespace.
Using AutoLoader
I will leave an example of simple use which is an index.php instantiating a class
Sample class
//src/Response.php
class Response
{
private $content;
public function setContent($content)
{
$this->content = $content;
}
public function flush()
{
echo $this->content;
}
}
Index
//index.php
require "vendor/autoload.php";
$response = new Response();
$response->setContent('teste');
$response->flush();
NOTE: This mini tutorial is valid for PHP > = 5.3, I do not know what the behavior is for older versions