Table of Contents
What is a PHP namespace?
Home Backend Development PHP Tutorial Introduction to PHP namespaces

Introduction to PHP namespaces

Jul 05, 2018 am 10:27 AM
Namespaces

This article mainly introduces the namespace of PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

What is a PHP namespace?

(PHP 5 >= 5.3.0, PHP 7)

What is a namespace? Broadly speaking, a namespace is a way of encapsulating things. This abstract concept can be found in many places. For example, directories are used in operating systems to group related files, and they act as namespaces for the files in the directory. For example, the file foo.txt can exist in the directories /home/greg and /home/other at the same time, but not in the same directory. There are two foo.txt files. In addition, when accessing the foo.txt file outside the directory /home/greg, we must put the directory name and directory separator before the file name to get /home/greg /foo.txt. The application of this principle to the field of programming is the concept of namespace.

In PHP, namespaces are used to solve two types of problems encountered when creating reusable code such as classes or functions when writing class libraries or applications:

  1. Name conflicts between user-written code and PHP internal classes/functions/constants or third-party classes/functions/constants.

  2. Create an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem), improve the source Code readability.

Although any legal PHP code can be included in a namespace, only the following types of code are affected by the namespace, which are: classes (including abstract classes and traits), interfaces, functions and constants.

The namespace is declared by the keyword namespace. If a file contains a namespace, it must declare the namespace before all other code except one: the declare keyword.

The only legal code before declaring a namespace is the declare statement used to define the source file encoding. In addition, all non-PHP code, including whitespace, cannot appear before the namespace declaration:

<html>
<?php
namespace MyProject; // 致命错误 - 命名空间必须是程序脚本的第一条语句?>
Copy after login

In addition, unlike other language features of PHP, the same namespace can be defined in multiple files, which allows Split the contents of the same namespace into different files.

1. Example 1
First we create two class files

a.php

<?phpclass Test
{    public function ceshi(){        echo __FILE__;
    }
}
Copy after login
Copy after login

b.php

<?phpclass Test
{    public function ceshi(){        echo __FILE__;
    }
}
Copy after login
Copy after login

index.php

<?php
require_once("a.php");
require_once("b.php");
Copy after login

Now run the index.php file

You will find a fatal error: Fatal error: Cannot redeclare class Test in. . . Obviously, the Test class cannot be redeclared because you introduced it twice, and the class names in the two files are the same, which conflicts. At this time, namespace is needed to solve this problem, and it is easy.

2. Example 2
We now slightly modify the two class files.

a.php

<?php
namespace demo1\a\Test;class Test
{    public function ceshi(){        echo __FILE__;
    }
}
Copy after login

b.php

<?php
namespace demo1\b\Test;class Test
{    public function ceshi(){        echo __FILE__;
    }
}
Copy after login

The namespace keyword is used to declare the namespace of. Now run index.php and find no errors. Modify index.php to perform method call test

index.php

<?php
require_once("a.php");
require_once("b.php");
$a1 = new demo1\a\Test\Test();
$a1->ceshi();
Copy after login

Now run index.php File

D:\phpStudy\WWW\demo\demo1\a.php

3. Example 3

Now there is another For example, if I need to instantiate the Test class in a.php multiple times, what should I do if it is troublesome to write the complete namespace information every time? For example:

<?php
require_once("a.php");
require_once("b.php");
$a1 = new demo1\a\Test\Test();
$a2 = new demo1\a\Test\Test();
$a1->ceshi();echo '
'; $a2->ceshi();
Copy after login

Although there is no error, you will find it more troublesome. You need to write the full namespace name every time. Although no error is reported and ctrl c, ctrl v can be used, it is not very beautiful (^_^ ).

You can do this

index.php

<?php
require_once("a.php");
require_once("b.php");
use demo1\a\Test\Test;
$a1 = new Test();
$a2 = new Test();
$a1->ceshi();
echo '
'; $a2->ceshi();
Copy after login

The use keyword is used to introduce classes and is represented by namespaces A certain class is used. You can directly instantiate the operation later

4. Example 5

Then another question comes again, as follows:

index.php

<?php
require_once("a.php");
require_once("b.php");
use demo1\a\Test\Test;
use demo1\b\Test\Test;
$a = new Test();
$b = new Test();
$a->ceshi();
echo '
'; $b->ceshi();
Copy after login

Now run the index.php file

## Fatal error: Cannot use demo1\b\Test\Test as Test because the name is already in use in D:\phpStudy\WWW\demo\demo1\index.php on line 5

Because although the namespace is used, However, the two classes have the same name, both are Test. The program does not know that the second Test class is the Test class in b.php. At this time, you use the as keyword

index .php

<?php
require_once("a.php");
require_once("b.php");
use demo1\a\Test\Test;
use demo1\b\Test\Test as bTest;
$a = new Test();$b = new bTest();
$a->ceshi();echo '
'; $b->ceshi();
Copy after login

The as keyword defines an alias for the class name, which can effectively prevent conflicts with the same class name

5. Example 6

For example, we create a global class file at the same level as a.php: c.php:

c.php

<?php
class Test{    
public function ceshi(){        
echo __FILE__;
    }
}
Copy after login

在index.php文件中这样做即可调用c.php中的test方法

<?php
require_once("a.php");
require_once("b.php");
require_once("c.php");
use demo1\a\Test\Test;
use demo1\b\Test\Test as bTest;
$a = new Test();$a->ceshi();
echo '
'; $b = new bTest(); $b->ceshi(); echo '
'; $c = new \Test(); $c->ceshi(); echo '
';
Copy after login

我们将这种类叫做全局类,如果要使用需要类前面加入反斜杠”\” 

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于PHP多态的理解

PHP文件编程的介绍

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solve PHP error: The specified namespace class was not found Solve PHP error: The specified namespace class was not found Aug 18, 2023 pm 11:28 PM

Solve PHP error: The specified namespace class was not found. When developing using PHP, we often encounter various error messages. One of the common errors is "The specified namespace class was not found". This error is usually caused by the imported class file not being properly namespace referenced. This article explains how to solve this problem and provides some code examples. First, let’s take a look at an example of a common error message: Fatalerror:UncaughtError:C

How to use namespace in F3 framework? How to use namespace in F3 framework? Jun 03, 2023 am 08:02 AM

The F3 framework is a simple, easy-to-use, flexible and scalable PHPWeb framework. Its namespace (Namespace) mechanism provides us with a more standardized, more readable, and clearer code structure. In this article, we will explore how to use namespaces in the F3 framework. 1. What is a namespace? Namespaces are often used to solve the problem of naming conflicts in PHP. It can encapsulate one or more classes, functions or constants in a namespace, which is equivalent to adding a prefix to them. example

Design ideas and implementation methods of Redis namespace and expiration mechanism Design ideas and implementation methods of Redis namespace and expiration mechanism May 11, 2023 am 10:40 AM

Redis is an open source, high-performance key-value storage database. When using Redis for data storage, we need to consider the design of the key namespace and expiration mechanism to maintain Redis performance and data integrity. This article will introduce the design ideas and implementation methods of Redis' namespace and expiration mechanism. 1. Redis namespace design ideas In Redis, keys can be set arbitrarily. In order to facilitate the management and distinction of different data types, Redis introduces the concept of namespace. Life

C++ syntax error: undefined namespace used, how to deal with it? C++ syntax error: undefined namespace used, how to deal with it? Aug 21, 2023 pm 09:49 PM

C++ is a widely used high-level programming language. It has high flexibility and scalability, but it also requires developers to strictly master its grammatical rules to avoid errors. One of the common errors is "use of undefined namespace". This article explains what this error means, why it occurs, and how to fix it. 1. What is the use of undefined namespace? In C++, namespaces are a way of organizing reusable code in order to keep it modular and readable. You can use namespaces to make functions with the same name

Example of new features in PHP8: How to use namespaces and codes to better organize the code structure? Example of new features in PHP8: How to use namespaces and codes to better organize the code structure? Sep 11, 2023 pm 12:22 PM

Example of new features in PHP8: How to use namespaces and codes to better organize the code structure? Introduction: PHP8 is an important version of the PHP programming language, which introduces many exciting new features and improvements. One of the most important new features is namespaces. Namespaces are a way to organize your code into a better structure that avoids conflicts between classes, functions, and constants with the same name. In this article, we’ll look at how to leverage namespaces and codes to better structure your PHP8 code

PHP 5.3 new feature: How to use namespaces to resolve class name conflicts PHP 5.3 new feature: How to use namespaces to resolve class name conflicts Jul 30, 2023 pm 12:25 PM

New features of PHP5.3: How to use namespaces to solve class name conflicts Introduction: During the development of PHP, as projects become larger and more complex, class name conflicts also arise. In order to solve this problem, PHP5.3 version introduced the concept of namespace. Namespaces provide a way to organize related classes, functions, and constants together to avoid naming conflicts. This article will introduce in detail the concept of PHP namespaces and how to use namespaces to solve class name conflicts, with code examples.

Methods to solve PHP namespace errors and generate corresponding error prompts Methods to solve PHP namespace errors and generate corresponding error prompts Aug 07, 2023 pm 05:16 PM

How to resolve PHP namespace errors and generate corresponding error messages. PHP is a widely used server-side scripting language that is used to develop web applications. In PHP, namespace (Namespace) is a mechanism for managing and organizing code, which can avoid naming conflicts and improve code readability and maintainability. However, the complexity of namespace definition and use sometimes leads to errors. This article will introduce some methods to solve PHP namespace errors and generate corresponding error prompts. 1. Name space

Best practices for PHP autoloading: ensuring stability and performance Best practices for PHP autoloading: ensuring stability and performance Mar 02, 2024 pm 09:10 PM

PHP Autoloading Overview Autoloading is a mechanism for automatically loading classes and their dependencies before use. In PHP, this is achieved by using the __autoload() function or an autoloader such as Composer. Proper autoloading settings are critical to ensuring the stability and performance of your codebase. PSR-4 automatic loading standard PSR-4 is the automatic loading standard defined by PHP-FIG. It is based on namespace and directory structure conventions to simplify class file lookup. To comply with PSR-4: define a root namespace (e.g. MyApp). Use backslash() as namespace separator. Use lowercase letters to represent namespace elements. Create a corresponding directory for each namespace element. General essay

See all articles