Home > Backend Development > PHP Tutorial > Introduction to php namespaces

Introduction to php namespaces

小云云
Release: 2023-03-22 17:32:01
Original
1655 people have browsed it

Why use namespaces? As the number of files in the project increases, it is inevitable that class names, function names, and constant names will be repeated. This article mainly shares with you an introduction to PHP namespaces, hoping to help everyone.

未定义命名空间的如下图
Copy after login

Fatal error: Cannot redeclare class test in E:\PHP\PHPTutorial\WWW\demo\namespace\b.php on line 2

How to use namespace

Define three files

a.php

namespace a\b;

class test{    public function show(){        echo 'this is a';    }}
Copy after login

b.php

<?phpnamespace c\d;class test{    public function show(){        echo &#39;this is b&#39;;    }}
Copy after login
index.php
require &#39;./a.php&#39;;
require &#39;./b.php&#39;;
Copy after login

$a = new a\b\test ();When instantiating a class, remember to add the namespace

Import the namespace

Since it is more cumbersome every time to instantiate the class, you can use the second way of writing

<?phpuse \a\b as w;require &#39;./a.php&#39;;require &#39;./b.php&#39;;$a = new w\test();$a->show();
Copy after login

1. The overall import of the space requires an alias. If there is no alias, the character after the last \ is used as the space name by default

Global space

The code behind namespace All belong to the current space, and the code outside the namespace belongs to the global space.

How to use the global space in the current space, just add \ backslash after the required members to indicate the global space.

Related recommendations:

Detailed explanation of PHP namespace and automatic loading examples

Completely master the PHP namespace

Detailed usage of PHP namespace

The above is the detailed content of Introduction to php namespaces. 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