Home >Backend Development >PHP Tutorial >Why can YIi2 use external objects without Include using namespaces?

Why can YIi2 use external objects without Include using namespaces?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-08-08 09:06:441432browse

As mentioned, I saw that in some Yii2 writing methods, namespaces can be loaded directly, such as:

<code> namespace web\models;
    
    use Yii; 
    use web\classes\CPost;
    
   //... code ...   
    
   $post = new CPost;</code>

In the above webmodels namespace, CPost objects can be created directly using the new keyword,
But I did a separate test of the namespace as follows:

<code> namespace web\models;

   // include "../classes/CPost.php";  这句必须取消注释才不报错
   use web\classes\CPost;

      class MPost {

        public function run(){
            echo "MPost->run()被调用";
        }

        public function getClassFunc(){
            $class = new CPost;
            $class->run();  //报错,提示找不到 web\classes\CPost对象
        }
    }
   
    $post = new MPost;
    $post->getClassFunc(); </code>

In the test code, if you do not inlucde the CPost file, an error will be reported.
But Yii2 does not introduce the file in the whole process, and you can directly create new objects using only the namespace.
Excuse me, what is going on and how is it done?

Reply content:

As mentioned, I saw that in some Yii2 writing methods, namespaces can be loaded directly, such as:

<code> namespace web\models;
    
    use Yii; 
    use web\classes\CPost;
    
   //... code ...   
    
   $post = new CPost;</code>

In the above webmodels namespace, CPost objects can be created directly using the new keyword,
But I did a separate test of the namespace as follows:

<code> namespace web\models;

   // include "../classes/CPost.php";  这句必须取消注释才不报错
   use web\classes\CPost;

      class MPost {

        public function run(){
            echo "MPost->run()被调用";
        }

        public function getClassFunc(){
            $class = new CPost;
            $class->run();  //报错,提示找不到 web\classes\CPost对象
        }
    }
   
    $post = new MPost;
    $post->getClassFunc(); </code>

In the test code, if you do not inlucde the CPost file, an error will be reported.
But Yii2 does not introduce the file in the whole process, and you can directly create new objects using only the namespace.
Excuse me, what is going on and how is it done?

spl autoload, learn composer by the way

Check the contents of the composer.json file. There is an autoload item in it to see if it defines automatic loading of the entire directory or just a few files.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn