If you need to order your code into namespaces, just use the keyword
namespace
:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use
use
. If in file2 you putuse foo\bar as mypath;
you need to use
mypath
instead of bar
anywhere in the file:$obj = new mypath\myObj();
Using
use foo\bar;
is equal to use foo\bar as bar;
.
The simplest way is to autoload each class separately. For this purpose, all we need to do is define the array of paths to the classes that we want to autoload in the composer.json file.
For example:
{
"autoload": {
"classmap": [
"path/to/FirstClass.php",
"path/to/SecondClass.php"
]
}
}
Update the composer autoloader from the command line:
$ composer dump-autoload -o
Now, we have to include the autoloader at the top of our scripts (e.g., index.php):
<?php
require "vendor/autoload.php";
In the same way that we autoload classes, we can autoload directories that contain classes also by using the classmapkey of the autoload:
{
"autoload": {
"classmap": [
"path/to/FirstClass.php",
"path/to/directory"
]
}
}
- In order to autoload directories we need to use namespaces.
As we can see, classmap autoloading is not much different than the long list of requires that we used to use in the older PHP scripts. Yet, the better way to autoload is by using the PSR-4 standard.
https://phpenthusiast.com/blog/how-to-autoload-with-composer
No comments:
Post a Comment