本文实例讲述了php命名空间namespace的定义方法。分享给大家供大家参考,具体如下:
定义命名空间
对于空间的命名,在此我想不用文字解释,更好的解释是用实例来证明:
for example:
下面这段代码是”test.php”里面的文件:
namespace test; class test{ public function ttest(){ echo "这是test里面的测试方法"."<br>"; } }
接下来我将用三种不同的方式进行访问,我把这三个访问程序写在一个名叫“index.php”的文件中:
方法一:
namespace index; require 'test.php'; $t=new \test\test(); $t->ttest();
所得结果为:
这是test里面的测试方法
方法二:
namespace index; namespace test; require 'test.php'; $t=new test(); $t->ttest();
所得结果为:
这是test里面的测试方法
方法三:
namespace index; require 'test.php'; use test\test; $t=new test(); $t->ttest();
所得结果为:
这是test里面的测试方法
注: namespace index可写可不写,这只是index.php文件的空间命名。这三种方法所得结果都是一样的。
定义子命名空间
定义:
与目录和文件的关系很象,php 命名空间也允许指定层次化的命名空间的名称。因此,命名空间的名字可以使用分层次的方式定义。
实例如下图,这是我自定义的项目目录:
one.php
namespace projectone\one; class test{ public function test(){ return "this is a test program"; } }
为了访问one.php中test类下的test()方法,我在two中的代码如下:
two.php
namespace projectone\one; require '../projectone/one.php'; $o=new test(); echo $o->test();
output: this is a test program
同一文件中定义多个命名空间,它们之间相互访问
test.php
namespace projectone\one{ class test{ public function hello(){ return "helloworld"; } } } namespace projectone\two{ class project{ public function world2(){ return "welcome to china"; } } class project2 extends \projectone\one\test{ public function wo(){ return "this is my test function ,it is name wo"; } } } namespace projectone\two{ $p=new project2(); echo $p->wo()."<br>"; echo $p->hello(); }
output: this is my test function ,it is name wo
helloworld
更多关于php相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《php基本语法入门教程》、《php运算与运算符用法总结》、《php网络编程技巧总结》、《php数组(array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
如何去设计前端框架能力?星巴克消息开放项目从0到1,从点到面的思考
PHP制作日历,实现在1970年到2020年之间的任何一个月份的输出。上半部分
网友评论