search

About PHP namespaces

May 14, 2018 pm 03:52 PM
phpnamespace

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

What is PHP namespace

PHP Manual: Broadly speaking, namespaces are 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.

The role of namespace

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) to improve the readability of the source code.

Example

I wrote this namespace article because a friend just learned this and asked me what a namespace is. I was wondering how to describe it simply and make it easy to understand. Below I will use a few simple examples to illustrate my own understanding of namespaces.

1. Example 1
First we create two class files
a.php

class Test{
    public function test()
    {
        echo "this is A class.";
    }
}

b .php

class Test{
    public function test()
    {
        echo "this is B class.";
    }
}

Create another index.php file to introduce the above two classes and call the methods in them.
index.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

namespace a\test;class Test{
    public function test()
    {
        echo "this is A class.";
    }
}

b.php

namespace b\test;class Test{
    public function test()
    {
        echo "this is B class.";
    }
}

The namespace keyword is used to declare the namespace. Now run index.php and find that there are no errors. Modify index.php to perform method call testing
index.php

require_once("a.php");require_once("b.php");$a = new a\test\Test();$a->test();//页面输出:this is A class.

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

require_once("a.php");require_once("b.php");$a = new a\test\Test();$a_a = new a\test\Test();$a_b = new a\test\Test();$a->test();$a_a->test();//页面输出:this is A class.this is A class.

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 you can ctrl c , ctrl v, but not very beautiful (^_^).
You can do this:
index.php

require_once("a.php");require_once("b.php");use a\test\Test;$a = new Test();$a_a = new Test();$a_b = new Test();$a->test();$a_a->test();//页面输出:this is A class.this is A class.

The use keyword is used to introduce a class and uses a namespace to indicate the use of a certain class. . You can directly instantiate the operation later
4. Example 5
Then another question comes, as follows:
index.php

require_once("a.php");require_once("b.php");use a\test\Test;use b\test\Test;$a = new Test();$b = new Test();$a->test();$b->test();

Obviously, another fatal error: Fatal error: Cannot use b\test\Test as Test because the name is already in use in. . . Because although the namespace is used, 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
For example:
index.php

require_once("a.php");require_once("b.php");use a\test\Test;use b\test\Test as BTest;$a = new Test();$b = new BTest();$a->test();$b->test();//页面输出:this is A class.this is B class.完美解决

The as keyword defines an alias for the class name, which can effectively prevent conflicts with the same class name
5. Example 6
The following is another situation. I will first give a few code snippets, which are in the Yii2 framework and have nothing to do with the framework. They are just for demonstration. This example can be seen in many places.

if (\Yii::$app->request->isPost) {
            $post = \Yii::$app->request->post();           ...
        }

Obviously a Yii class is used here, but why is there a backslash "\" in front of it? Let's track the Yii class first. Some students will ask how to track it. If you are using PHPstormEditor, just hold down Ctrl and click the class name with the mouse to jump to such class file. For how to use the PHPstorm editor, please check: PhpStorm cracked version and usage tutorial
The following is the Yii class file code snippet:

/**
 * Yii bootstrap file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */require(__DIR__ . '/BaseYii.php');class Yii extends \yii\BaseYii{
}

You will find that the Yii class does not have a namespace. We call this class a global class. If you want to use it, you need to add a backslash "\" in front of the class.
For example, we create a global class file at the same level as a.php: c.php:

class Test{
    public function test()
    {
        echo "this is C class.";
    }
}

Do this in the index.php file to call the test method in c.php

require_once("a.php");
require_once("b.php");
require_once("c.php");
use a\test\Test;use b\test\Test as BTest;
$a = new Test();$b = new BTest();
$c = new \Test();
$a->test();$b->test();
$c->test();
//页面输出:
this is C class.this is A class.this is B class.this is C class.

Note: the usage of keywords such as namespace, use, as and the use of global classes.

What is a PHP namespace

PHP Manual: 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.

The role of namespace

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) to improve the readability of the source code.

示例

写这个命名空间的文章是因为一个朋友刚学这个来问我命名空间到底是个什么东西。我在想怎么简单的描述出来并且很容易理解。下面我就以几个简单的小例子来说明一下我自己对命名空间的理解。

1. 例一
首先我们先建立两个类文件
a.php

class Test{
    public function test()
    {
        echo "this is A class.";
    }
}

b.php

class Test{
    public function test()
    {
        echo "this is B class.";
    }
}

再建立一个index.php文件,来引入以上两个类并调用其中的方法。
index.php

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

现在运行index.php文件,你会发现有一个致命错误: Fatal error: Cannot redeclare class Test in。。。很显然,无法重新声明Test类,因为你引入了两次,而且两个文件中的类名称相同,冲突了。这个时候就需要命名空间来解决这个问题,并且很容易。
2. 例二
我们现在把两个类文件稍作修改。
a.php

namespace a\test;class Test{
    public function test()
    {
        echo "this is A class.";
    }
}

b.php

namespace b\test;class Test{
    public function test()
    {
        echo "this is B class.";
    }
}

namespace关键字是用来声明命名空间的。现在运行index.php发现没有错误,修改index.php进行方法调用测试
index.php

require_once("a.php");require_once("b.php");$a = new a\test\Test();$a->test();//页面输出:this is A class.

3. 例三
现在有另外一种情况,比如我需要实例化a.php中的Test类多次,那么每次我们都需要命名空间信息完整写的话比较麻烦怎么办呢?比如:
index.php

require_once("a.php");
require_once("b.php");
$a = new a\test\Test();
$a_a = new a\test\Test();
$a_b = new a\test\Test();
$a->test();
$a_a->test();
//页面输出:
this is A class.this is A class.

虽然也没有错误,但是你会发现比较麻烦,每次都需要全写命名空间名称,虽然不报错并且可以ctrl+c,ctrl+v,但是不太美观(^_^)。
你可以这样做:
index.php

require_once("a.php");
require_once("b.php");
use a\test\Test;
$a = new Test();
$a_a = new Test();
$a_b = new Test();
$a->test();
$a_a->test();
//页面输出:
this is A class.this is A class.

use关键字是用来引入类,用命名空间的方式表示使用了某个类。后面就可以直接实例化操作
4. 例五
接下来另一个问题又来了,如下:
index.php

require_once("a.php");require_once("b.php");use a\test\Test;use b\test\Test;$a = new Test();$b = new Test();$a->test();$b->test();

很明显,又一个致命错误:Fatal error: Cannot use b\test\Test as Test because the name is already in use in 。。。因为虽然使用了命名空间,但是两个类名称相同,都是Test,程序不知道第二个Test类是b.php中的Test类,这时候你就用到了as关键字
如:
index.php

require_once("a.php");
require_once("b.php");
use a\test\Test;
use b\test\Test as BTest;
$a = new Test();
$b = new BTest();
$a->test();$b->test();
//页面输出:
this is A class.this is B class.完美解决

as关键字是对类名称定义别名,可以有效防止类名称相同冲突
5. 例六
下面是另一种情况,我先给出几个代码片段,是Yii2框架中的,和框架无关,只是为了演示使用,很多地方都能见到此例。

if (\Yii::$app->request->isPost) {
            $post = \Yii::$app->request->post();           ...
        }

很显然这里使用了一个Yii类,但是为什么前面又一个反斜杠”\”,我们先追踪一下Yii类,有的同学会问怎么追踪呢,如果你使用的是PHPstorm编辑器,直接按住Ctrl,鼠标点击类名就会跳到此类类文件中,关于怎么使用PHPstorm编辑器,请查看:PhpStorm破解版及使用教程
下面是Yii类文件代码段:

/**
 * Yii bootstrap file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */require(__DIR__ . '/BaseYii.php');class Yii extends \yii\BaseYii{
}

你会发现该Yii类并没有命名空间,我们将这种类叫做全局类,如果要使用需要类前面加入反斜杠”\”
比如我们在a.php同级再建立一个全局类文件:c.php:

class Test{
    public function test()
    {
        echo "this is C class.";
    }
}

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

require_once("a.php");
require_once("b.php");
require_once("c.php");
use a\test\Test;
use b\test\Test as BTest;
$a = new Test();
$b = new BTest();
$c = new \Test();
$a->test();
$b->test();
$c->test();
//页面输出:
this is C class.this is A class.this is B class.this is C class.

注意:namespace,use,as等关键字用法以及全局类的使用。

The above is the detailed content of About 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 can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

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.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)