Home  >  Article  >  Backend Development  >  三种施用php namespace的方法

三种施用php namespace的方法

WBOY
WBOYOriginal
2016-06-13 11:01:22881browse

三种使用php namespace的方法
PHP 5.3中的namespace其实是个不错的东西,可以简化编程,下面介绍三类在代码中
访问namespace中类的方法

1 引用namespace和类
  假设namespace的程序为namespaced-class.php
namespace Christmas\DaysOf; 

class PartridgeInAPearTree{
}


  引用方法:
  include 'namespaced-class.php';

$bird1 = new Christmas\DaysOf\PartridgeInAPearTree();
var_dump($bird1);

这个时候,NEW的时候把完整的namespace及下面的类都引入进来了

2 部分引用
   include 'namespaced-class.php';
use Christmas\DaysOf;

$bird2 = new DaysOf\PartridgeInAPearTree();
var_dump($bird2);
这里USE指定了命名空间后,在使用时,只需要引用命名空间的最后部分Daysof即可.

3 最简单的
   include 'namespaced-class.php';
use Christmas\DaysOf\PartridgeInAPearTree as Bird;           

$bird3 = new Bird();
var_dump($bird3);

这里把命名空间下的指定类都用一个自定义的名称来代替了,十分方便


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn