Home > Backend Development > PHP Problem > How to introduce another space element in a namespace?

How to introduce another space element in a namespace?

autoload
Release: 2023-03-08 15:36:01
Original
1623 people have browsed it

Space introduction method: use use keywords

<?php
namespace n1;
class OK{};
namespace n2;

//一种方式
new \n1\OK();

//第二种方式  
use n1\OK;
new OK();
?>
Copy after login

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();
?>
Copy after login

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
};	
?>
Copy after login


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();
?>
Copy after login

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();                //使用引入空间的最后一级空间访问

?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template