tp5 namespace

Namespace
ThinkPHP5 uses namespaces to define and automatically load class library files, which effectively solves the problem of namespace conflicts between multiple modules and Composer class libraries, and implements a more efficient class library automatic loading mechanism.
Special attention is that if you need to call PHP's built-in class library, or a third-party class library that does not use namespaces, remember to add \ when instantiating the class library, for example:
// wrong usage
$class = new stdClass();
$xml  =  new SimpleXmlElement($xmlstr);
// correct usage
$class = new \stdClass();
$xml  =  new \SimpleXmlElement($xmlstr);

In ThinkPHP5.0, you only need to correctly define the namespace where the class library is located, and the path of the namespace is consistent with the directory of the class library file, then the automatic loading of the class can be realized, so as to realize the real lazy loading.

For example, the \think\cache\driver\File class is defined as:

namespace think\cache\driver;

class File
{
}


If we instantiate the class, it should be:
$class = new \think\cache\driver\File();

The system will automatically load the class file corresponding to the path of this class, and its path is thinkphp/library/think/cache/driver/File.php.
    The default directory specification in 5.0 is lowercase, class file names are camelCase, and the first letter is capitalized.
In principle, directories named in camel case can be supported, as long as the namespace definition is consistent with the directory, for example:

we instantiate

$class = new \Think\Cache\Driver\File();

the system will automatically load thinkphp/library/ Think/Cache/Driver/File.php file.

Automatic registration

We only need to put our class library package directory into the EXTEND_PATH directory (the default is extend, configurable), and the corresponding namespace can be automatically registered. For example:

we add a my directory under the extend directory, and then define a The \my\Test class (the class file is located in extend/my/Test.php) as follows:
namespace my;

class Test
{
    public function sayHello()
    {
        echo 'hello';
    }
}


We can then instantiate and call directly:
$Test = new \my\Test();
$Test->sayHello();


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326524910&siteId=291194637