php设计模式--命名空间与自动载入
关于命名空间:
最早的php是没有命名空间的概念的,这样不能存在相同名称的类或者函数,当项目变大了之后,产生冲突的可能性就高了,代码量也会变大,为了规划,从php5.3开始对命名空间就支持了。
说明代码:
1 2 3 4 5 6 7 | test1.php<br><?php //声明命名空间 namespace Test1; function test(){ echo "test1<br/>" ; } |
1 2 3 4 5 6 7 8 | test2.php <?php //声明命名空间 namespace Test2; function test(){ echo "test2<br/>" ; } |
将test1.php ,test2.php引入到test.php中:
1 2 3 4 5 6 7 8 9 | test.php <?php //引入test1,test2 require 'test1.php' ; require 'test2.php' ; //命名空间的使用 Test1\test(); Test2\test(); |
如果不使用命名空间,显而易见php会报函数名重复致命错误,如果使用命令空间结果如下:
1 2 | test1 test2 |
关于自动载入:
之前的php都是通过include或者require来引入php的,当项目越来越大的时候,如果一个php文件需要引入几十个php类的时候,那就会引入几十行,这样对管理代码和开发来说是很不方便的。在php5.2之后就提供了类的自动载入功能。
在php5.2中提供了__autoload 方法来引入,但是当多个php文件同时使用此方法时会有函数名重复的可能,在php5.3中这个函数被废弃了,系统提供了一个spl_auto_register()的方法。当换成spl_auto_register自动载入类之后,可避免冲突。
1 2 3 4 5 6 7 | Test3.php<br> class Test3 { static function test() { echo "test3-class<br/>" ; } } |
1 2 3 4 5 6 7 8 | Test4.php<br><?php class Test4 { static function test() { echo "test4-class<br/>" ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php spl_autoload_register( 'autoload1' ); //函数名作为参数传入 spl_autoload_register( 'autoload2' ); //函数名作为参数传入可支持多个 Test3::test(); Test4::test(); function autoload1( $class ) { require __DIR__. '/' . $class . '.php' ; } function autoload2( $class ) { require __DIR__. '/' . $class . '.php' ; } |
结果如下:
1 2 | test3- class test4- class |
* 当php执行过程中发现你使用的类并不存在,这时候,php会把那个类名(Test3)告诉自动载入函数(autoload),然后我们只需要引入相关类就可以了。
总结:命名空间和自动载入对我们写好面向对象开发是很重要的。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步