As a package management tool for PHP, Composer provides phPers with a rich library of classes and helps PHP avoid the tragedy of being obsolete. If you haven’t used Composer or worked in PHP7, you may be a little behind The Times.

This series of articles will analyze the principle of Composer step by step, and will not explain the command of Composer or how to use it. You can work on this aspect of Composer: www.phpcomposer.com/


The first part focuses on a simple function: the __autoload() magic method


      

$m = new TestClass();
$m->show();

function __autoload($className)
{
    require $className . '.php';
}

Copy the code

To learn programming, the first step is to type out the code. Create a new document called autoload.php and copy the code in it.

Then create a new testclass.php file in the same directory as testclass.php and put the following code in testclass.php:


      

class TestClass
{
    public function show(a)
    {
        echo 'we are family! '; }}Copy the code

Next, you can access autoload.php from the web or, as I recommend, from the command line: php./ autoload.php

Instead of explicitly using functions like require() and include above autoload.php, we use require $className. ‘.php’ in __autoload(); With this statement, the testclass.php file is loaded.

Yes, as I’m sure you’ve guessed, the function of the magic method __autoload() is to enter it if the calling class is not loaded.

It is defined as such in the official PHP documentation

An undefined class was attempted to load

Function format

__autoload( string $class ) : void

  • The $class argument is the name of the class that is not loaded, which is TestClass at the top
  • The return value is null
  • In general, the specified file is loaded within the function according to the $class

This method will be DEPRECATED after PHP7.2 and may be removed in a future release. The spl_autoload_register() function, which we’ll cover in the next article, is the future of autoloading. Advantage of using autoload functions: you don’t need a bunch of require at the top of the file.

Well, we’ve seen what __autoload() does, but what does this have to do with Composer?

Don’t worry, any great technology always has a foundation, without this condition, the technology is difficult to achieve, just like artificial intelligence, although there have been a variety of algorithms and theories, but before the big data technology always can not be landed. Because machine learning requires a lot of data access is difficult. Here, Composer is like AI technology, and the __autoload() method is the building block.

Full source: GitHub