手机
当前位置:查字典教程网 >编程开发 >php教程 >php中namespace use用法实例分析
php中namespace use用法实例分析
摘要:本文实例讲述了php中namespaceuse用法。分享给大家供大家参考,具体如下:现在说这个感觉有点过时了,但是感觉用namespace的...

本文实例讲述了php中namespace use用法。分享给大家供大家参考,具体如下:

现在说这个感觉有点过时了,但是感觉用namespace的人还是不多,估计还是因为不习惯吧。

class把一个一个function组织起来,namespace可以理解成把一个一个class,function等有序的组织起来。个人觉得,namespace的主要优势有

第一,可以更好的管理代码

第二,文件一多,可以避免class,function的重名

第三,代码可读性增强了

1. 定义namespace

namespace userCenter; //php代码 namespace userCenterregister; //php代码 namespace userCenterlogin { //php代码 }

命名空间不能嵌套或在同一代码处声明多次(只有最后一次会被识别)。但是,你能在同一个文件中定义多个命名空间化的代码,比较合适的做法是每个文件定义一个命名空间(可以是相同命名空间)。

2. 调用namespace

userCenterregister; //绝对调用 userCenterlogin; //相对调用 use userCenterregister; //引用空间 use userCenterregister as reg; //引用空间并加别名

3. 实例说明

login.class.php

<?php namespace userCenter; function check_username(){ echo "login OK<br>"; } class login{ public function save(){ echo "login had saved<br>"; } } ?>

regist.class.php

<?php namespace userCenterregist { function check_username() { echo "regist OK<br>"; } class regist{ public function save(){ echo "regist had saved<br>"; } } } ?>

test.php

<"login.class.php"; require "regist.class.php"; use userCenterregist; //使用use调用空间 use userCenterregist as reg; //as定义别名 echo userCentercheck_username(); //绝对调用 $login = new userCenterlogin(); echo $login->save(); echo registcheck_username(); //相对调用 echo regcheck_username(); //别名调用 $regist = new regregist(); echo $regist->save();

使用use,比绝对调用要好一点,好比给class,function等加了一个前缀,这样看起来就比较清楚了。

希望本文所述对大家PHP程序设计有所帮助。

【php中namespace use用法实例分析】相关文章:

php中smarty变量修饰用法实例分析

php中memcache 基本操作实例

php curl 上传文件代码实例

php实现简单的语法高亮函数实例分析

PHP生成器简单实例

PHP中isset与array_key_exists的区别实例分析

php操作memcache缓存方法分享

php使用GD实现颜色渐变实例

PHP中的traits实现代码复用使用实例

php线性表的入栈与出栈实例分析

精品推荐
分类导航