If you no longer want to have problems with this type of situation I recommend using an Autoloader ready. My tip is to use the Composer, for this you have to install the same.
Installing the Composer
To install Composer just run a command line, nothing else! There are other ways to install Composer, more I’ll show you what 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 for it put its folder in environment variables or pass its path when executing the command.
Ready now you have Composer installed in your project! Now we just need to ask him to install the dependencies in his project and when installing the dependencies he will install an Autoloader automatically.
Installing the 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": {}
}
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
That will depend on your intention.
Alternate configuration
You can configure your project’s Autoloader, a configuration I use is as follows::
"autoload": {
"psr-0": {
"": "src/"
}
},
Now I can leave my sources inside the directory without having to include it in the namespace.
Using the Autoloader
I’ll leave an example of simple usage which is an index.php instantiating a class
Example 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 don’t know how it is for older versions
could use the function realpth() to "canonize".
– Daniel Omine
Almost there... Canonize ^_^
– Bruno Augusto
@Danielomine almost there² : realpath() xD
– gmsantos
haha sorry, I didn’t know how to write in English, so I put in quotes.
– Daniel Omine