search
HomeBackend DevelopmentPHP TutorialComplete usage of PHP command space

Complete usage of PHP command space

Dec 20, 2017 pm 02:55 PM
phpEncyclopediausage

We know that in namespaceone of the clearest purposes is to solve the problem of duplicate names, so in PHP, two functions or classes are not allowed to have the same name, otherwise a fatal error will occur. . In this case, it can be solved as long as you avoid naming duplication. The most common way is to agree on a prefix.

The purpose of using namespace:

When working on a team project, avoid conflicts with classes created by other team members; when individuals are responsible for the project, avoid creating new classes before and after There is a conflict between classes;

According to my personal understanding, when using the required class, it needs to be introduced by require or include first, so the premise for a class redefinition error to occur is: two classes with the same name have be introduced. Currently, some PHP frameworks will

automatically load (i.e. include) all newly created model classes, so in order to avoid duplicate name conflicts between your new model classes and the native core classes of the project framework, namespace is used. (After thinking about it, conflicts with new classes created by team members should be avoided through communication. Even after the incident, the class name should be readjusted and maintained immediately to avoid increased maintenance complexity caused by confusion in the understanding of the class later.)

Combined with the usage methods to further understand its purpose.

How to use namespace:

In order to test, I will create 3 files: 1.php and name.php (this file is used to perform testing), which will not be explained later. Please note the code changes yourself.

1. The definition of the name after namespace is not case-sensitive

namespace one;

namespace One;
namespace ONE;

You can write it the same way as above, choose Just use one as your own standard. (I will use the first method for testing in the following code)

2. If there is no namespace defined, it is understood that the top-level namespace is used. When creating a new class, you can add a backslash\ before the class or not.

//1.php
class Person{
 function construct(){
  echo 'I am one!';
 }
}
//name.php
require_once './1.php';
new Person(); //输出 I am one!;
new \Person(); //输出 I am one!;

3. When adding a namespace to a new class, backslash characters must be used instead of forward slashes.

Memory method: Find the order of slashes in % and interpret them as forward slashes. (Sometimes when talking about backslashes, I don’t even know which direction it is. I used to remember it in the ascending direction from left to right, but now I feel that this is too unreliable)

//name.php
require_once './1.php';
new /Person(); // 代码报错:Parse error: syntax error, unexpected '/'

4. Classes are specified in Under the namespace, when adding a new class, the specified namespace must be included.

Without the specified namespace, according to point 2, PHP will find this class from the top-level namespace. Remember: This cannot be understood as the top-level namespace includes all other namespaces. Instead, top-level namespaces should be completely separated from other namespaces.

/1.php
namespace one;
class Person{
 function construct(){
  echo 'I am one!';
 }
}
//name.php
require_once './1.php';
new \one\Person(); //输出 I am one!;
new \Person(); //代码报错:Fatal error: Class 'Person' not found

You can take this popular example to understand: bringing the specified namespace represents someone's apples (in his hand), and the top-level namespace represents the apples in the apple box (in the box). Now if you want to find someone's apple, you need to bring someone's namespace. Otherwise, you will look for someone's apple from the box, and of course you can't find it.

5. The code after the namespace declaration belongs to this namespace, even if there is include or require, it will not be affected (the focus is on the understanding of the second half of the sentence, see the code for details).

//1.php
namespace one;
class Person{
 function construct(){
  echo 'I am one!';
 }
}
//name.php
namespace test;
require './1.php';
new \one\Person(); //输出 I am one!;
new Person(); //这里结果会是什么呢,猜猜看

The last line results in an error:

Fatal error: Class 'test\Person' not found

First of all, compare this with the second point:

The second point, I said, when there is no namespace, when the new class , the meaning is the same with or without the backslash.

Here, with the namespace, the meaning of having and not having backslashes is different.

Replace the last line with

new \Person();

and the result is an error:

Fatal error: Class 'Person' not found

Then, let’s talk about the current point.

We can find that the namespace corresponding to the last line of code is test and is not affected by the namespace in the require file.

To further strengthen the verification, I modified the name.php file as follows:

//name.php
namespace test;
require './1.php';
class Person{
 function construct(){
  echo 'I am test!';
 }
}
new \one\Person(); //输出 I am one!;
new Person(); //这里结果会是什么,自己猜猜看

Finally, this example refreshed my understanding of require.

According to my previous understanding of require: before the PHP program is executed, it will first read in the file specified by require, making it a part of the PHP program web page. So I often simply understand it as replacement, which is just putting the extracted code back into its original place. Then I tried to put the contents of the 1.php file into name.php:

//name.php
namespace test;
namespace one;
class Person{
 function construct(){
  echo 'I am one!';
 }
}
class Person{
 function construct(){
  echo 'I am test!';
 }
}

Without the new class, the file will report an error:

Fatal error: Cannot redeclare class one\Person

It seems that simply understanding require as replacement will not work here.

6. The namespace does not contain the class name. Even if there is a part with the same name as the class name, it does not represent the class. new class, you still have to bring this part.

//name.php
namespace test\person;
class Person{
 function construct(){
  echo 'I am test!';
 }

}new \test\person\Person(); //person cannot represent the class name in the namespace

But this is purely superfluous, just don’t include the class name in the namespace Just fine.

7. Multiple namespaces can exist in a php file, and there cannot be any code before the first namespace.

It only says that there cannot be any code before the first namespace, and there can be code before subsequent namespaces. You can test this yourself.

//name.php
namespace test;
echo 'zhai14';
namespace zhai;
require './1.php';


php namespacenamespace has come to an end, let’s talk about the use of use.

使用use的目的:

在命名空间字符串过长时,使用use可以相应的缩短命名空间。

use的使用方法:

1.new类时,最前面无需用反斜杠。此外,use后没有as时,缩短的命名空间默认为最后一个反斜杠后的内容。

//name.php
namespace animal\dog;
class Life{
 function construct(){
  echo 'dog life!';
 }
}
namespace animal\cat;
class Life{
 function construct(){
  echo 'cat life!';
 }
}
new Life(); //按照代码执行顺序,这里默认animal\cat这个命名空间
new \animal\dog\Life(); //A
use animal\dog; //a
new dog\Life(); //B
use animal\dog as d; //b
new d\Life();


 通过A、B行代码比较,需要注意:

使用use后,new类时,最前面没有反斜杠。

没使用use时,命名空间最前面有反斜杠

通过a、b行代码比较,可以理解:

use后没有as时,缩短的命名空间默认为最后一个反斜杠后的内容。如上的:

use animal\dog;

相当于

use animal\dog as dog;

2.namespace后面不建议加类名,但use后可以。

//name.php
namespace animal\dog;
class Life{
 function construct(){
  echo 'dog life!';
 }
}
namespace animal\cat;
class Life{
 function construct(){
  echo 'cat life!';
 }
}
use animal\dog\Life as dog;
new dog();


如上所示,use后加上类名后,就相当于把类改了个名称:由Life改为dog了。

上面不用as dog就会报错:

Fatal error:  Cannot use animal\dog\Life as Life because the name is already in use


因为cat下也有个一样名称的Life类。

可以理解为,使用use后,这个昵称对应的类只能归当前命名空间占有,其它命名空间下不允许存在该类。

//name.php
namespace animal\dog;
class Life{
 function construct(){
  echo 'dog life!';
 }
}
class Dog{
 function construct(){
  echo 'dog in dog!';
 }
}
namespace animal\cat;
// class Dog{
// function construct(){
//  echo 'dog in cat!';
//  }
// }
class Life{
 function construct(){
  echo 'cat life!';
 }
}
use animal\dog;
new dog\Dog();


如上,使用了

use animal\dog;
 cat

通过上面代码,我想使用use的目的效果(缩短命名空间名称)就很明显了。

简单总结一下:

namespace就是划分领域的作用,代表这些东西是属于某个命名空间下的。


相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

php自定义函数生成笛卡尔积的方法

PHP自定义函数生成笛卡尔积

多个数组求笛卡尔积


The above is the detailed content of Complete usage of PHP command space. 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

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment