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

Introduction to php namespaces

小云云
小云云Original
2018-03-29 17:03:491661browse

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.

未定义命名空间的如下图

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';    }}

b.php

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

$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

ba0bf9f6a66d5f65ad2b51a4d38cbdb0show();

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!

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