php中namespace use用法实例分析

yipeiwu_com5年前PHP代码库

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

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

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

第一,可以更好的管理代码
第二,文件一多,可以避免class,function的重名
第三,代码可读性增强了

1. 定义namespace

namespace userCenter;
//php代码
namespace userCenter\register;
//php代码
namespace userCenter\login {
 //php代码
}

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

2. 调用namespace

\userCenter\register; //绝对调用
userCenter\login; //相对调用
use userCenter\register; //引用空间
use userCenter\register 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 userCenter\regist
{
 function check_username() {
 echo "regist OK<br>";
 }
 class regist{
 public function save(){
 echo "regist had saved<br>";
 }
 }
}
?>

test.php

<?php
require "login.class.php";
require "regist.class.php";
use userCenter\regist; //使用use调用空间
use userCenter\regist as reg; //as定义别名
echo \userCenter\check_username(); //绝对调用
$login = new \userCenter\login();
echo $login->save();
echo regist\check_username(); //相对调用
echo reg\check_username(); //别名调用
$regist = new reg\regist();
echo $regist->save();

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

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

相关文章

php密码生成类实例

本文实例讲述了php实现的密码生成类及其应用方法,分享给大家供大家参考。具体分析如下: 一、php密码生成类功能: 1.可设定密码长度。 2.可设定要生成的密码个数,批量生成。 3.可以...

PHP 等比例缩放图片详解及实例代码

PHP 等比例缩放图片详解及实例代码

直接上代码,imgzip($src,$newwid,$newhei)这个函数带进去的分别是原图片、缩放要求的宽度、缩放的长度。代码都备注了,不懂可以留言哈哈 <?php...

php购物网站支付paypal使用方法

详细参考: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_htm...

php提示undefined index的几种解决方法

php提示undefined index的几种解决方法

平时用$_post[''],$_get['']获取表单中参数时会出现Notice: Undefined index: --------; 我们经常接收表单POST过来的数据时报Undef...

PHP在同一域名下两个不同的项目做独立登录机制详解

PHP在同一域名下两个不同的项目做独立登录机制详解

前言 目前有这样一个需求,在一个域名下 如:http://example.com 下,有两个项目,example.com/a/,example.com/b/,这两个项目是相互独立的程序,...