search
HomeBackend DevelopmentPHP TutorialIntroduction 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; // 致命错误 - 命名空间必须是程序脚本的第一条语句?>

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

b.php

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

index.php

<?php
require_once("a.php");
require_once("b.php");

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

b.php

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

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();

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();

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();

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();

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();

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注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
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool