Home > Article > Backend Development > How to introduce another space element in a namespace?
Space introduction method: use use
keywords
<?php namespace n1; class OK{}; namespace n2; //一种方式 new \n1\OK(); //第二种方式 use n1\OK; new OK(); ?>
The elements introduced by space are classes by default. If you want to introduce other elements, you must use the corresponding keywords : function
and const
(if you need to introduce multiple elements of the same type, you need to use ",
" to separate them)
<?php namespace n1; class OK{}; function display(){ echo "display"; } const P=10; const A=11; namespace n2; use n1\OK; //引入类 use function n1\display; //引入函数 use const n1\A,n1\P; //引入常量,可以同时引入多个 display(); echo P; new OK(); ?>
If You need to add multiple elements at the same time
<?php namespace n1; class OK{}; function display(){ echo "n1中的display"; } const P=10; const A=11; namespace n2; use n1\{ OK, const P, const A }; ?>
If the introduced element already exists in the current space, there will be duplicate names. The solution is to use aliasesas
Keyword for renaming
<?php namespace n1; class OK{}; function display(){ echo "n1中的display"; } const P=10; const A=11; namespace n2; function display(){ echo "n2中的display"; } use n1\OK; //引入类 use function n1\display as display2;//引入函数 use const n1\P,n1\A; //引入常量 display2(); echo P." ".A; new OK(); ?>
If all elements in a space need to be introduced, you can also directly introduce space
<?php namespace n1\n2; class OK{ public function __construct() { echo __NAMESPACE__."<br>"; } } namespace n2; class OK{ public function __construct() { echo __NAMESPACE__."<br>"; } } //引入空间 use n1\n2; new OK(); //访问的是n2\OK new n2\OK(); //使用引入空间的最后一级空间访问 ?>
Recommended: php tutorial ,php video tutorial
The above is the detailed content of How to introduce another space element in a namespace?. For more information, please follow other related articles on the PHP Chinese website!