Blogger Information
Blog 17
fans 0
comment 0
visits 12599
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
细说名命空间学习心得
越努力越幸运
Original
567 people have browsed it

//非限定名称:


namespace ns2;


     class Demo2{

    

     }

     echo Demo2::class.'是非限定名称<br>' ;


namespace ns3\first;


     class Demo3{

    

     }

     echo first\Demo3::class .'是限定名称<br>';

namespace ns4;


     echo \ns3\first\Demo3::class.'是完全限定名称<br>' ;

    

    //匿名空间就是全局空间;访问时就用反斜杠:\;

    //多个命名空间用大括号如:namespace ns1{}    namespace ns2{}

    

//别名


//命名空间别名


namespace ns5;

     class Demo5{

         public function say(){

              return '别名';

         }

     }


//类别名:提倡用,避免名字冲突

namespace ns6;

     use ns5 as t5;

     echo t5\Demo5::say().'<br>';

    

     use ns5\Demo5 as t6;

     echo t6::say().'<br>';

    

    

     use ns5\Demo5;

     echo Demo5::say().'<br>';


//自动加载的两个条件:

//1.命名空间必须和类文件所在的绝对路径一一对应;

//2.当前类名称与当前的类文件的名称完全一致;


//举例:inc\lib:

/*

     require 'inc/lib/D1.php';

     require 'inc/lib/D2.php';

     require 'inc/lib/D3.php';

    

    

     echo \inc\lib\D1::class ,'<br>';

     echo \inc\lib\D2::class ,'<br>';

     echo \inc\lib\D3::class ,'<br>';

*/

//优雅的写法:

/*

     use inc\lib\D1;

     use inc\lib\D2;

     use inc\lib\D3;

    

     echo D1::class,'<br>';

     echo D2::class,'<br>';

     echo D3::class,'<br>';

*/

//自动加载:


     echo __DIR__;

     echo '<hr>';

    

     $classname='inc\lib\D1';

//步骤:

     //1.将类名中的命名空间分隔符(反斜线)转变为目录分隔符:

     //window:反斜线;linux:正斜线;

     //DIRECTORY_SEPARATOR:目录分隔符;

    

     $path=str_replace('\\', DIRECTORY_SEPARATOR, $classname);

     echo $path,'<br>';

    

     //2.生成真正要加载的类文件名称

     $file=__DIR__.DIRECTORY_SEPARATOR.$path.'.php';

     echo $file,'<br>';

    

     //3.加载这个文件

     require $file;

    

     use inc\lib\D1;

     echo D1::say();


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post