相关学习推荐:php编程(视频)
一直对PHP的命名空间没有全面的了解,只知道是一种可以避免命名冲突的语法结构或特性,下面是我在PHP官网结合实际操作上,来帮助自己理解namespace;
如果有不对的地方,欢迎大家来纠正,谢谢各位大佬!
来源
命名空间是一种抽象的分层,或者说封装的概念;比如文件系统中,hello.php可以在/www/a/和/www/b/两个目录其下存在,但是不能在一个目录下,有两个相同的hello.php;
其次,www/a/ 下可以直接访问到hello.php,但是在a外面的其他目录中,直接访问hello.php,是出错的,因为系统并不知道要访问的文件就是www/a/hello.php;必须得加上一个指定的路径,绝对,相对路径都行;命名空间就借鉴了这种逻辑概念;
为什么说是逻辑概念?因为文件系统本身也是一种虚拟的,抽象的,实际的磁盘是分为n个block块,是没有直接的这种目录结构概念
解决的问题
- 自己写的代码中,与PHP内置(或第三方)的类,函数,常量 之间的命名冲突;
比如说, 载入一个redis的DB类,但是又自己写了一个mysql的DB类,此时,类名相同,必然产生冲突,此时如果将两个类划分到不同的命名空间中,比如 DB\redis\connClass , DB\mysql\connClass,则避免了这种问题 - 为很长的名称创建别名,提高代码可读性;
比如说,一个类名是UserInformationCenter,假如命名空间在 App\Controller\,那么使用时,要写 App\Controller\UserInformationCenter ,不利于可读性,因此可以加一个简短的别名,App\Controller\UserInformationCenter as UIC;
# 使用示例namespace my\name; //声明一个命名空间,下面的代码属于这个命名空间内class MyClass {} //实际 : my\name\Myclass{}function myfunction() {} // my\name\myfunction()const MYCONST = 1; // my\name\MYCONST$a = new MyClass; //实例化的类是 my\name\Myclass{}$b = new \my\name\MyClass; //object(my\name\MyClass)#2 (0) {}$c = strlen('hi'); //全局空间下,前面省略了 \$d = namespace\MYCONST; //namespace关键字获取的就是当前的命名空间名称$e = __NAMESPACE__ . "\MYCONST";echo "<pre class="brush:php;toolbar:false">";var_dump($a, $b, $c ,$d ,$e);echo constant($e);/*object(my\name\MyClass)#1 (0) { } object(my\name\MyClass)#2 (0) { } int(2) int(1) string(15) "my\name\MYCONST" 1 */
注意:名为PHP或php的命名空间,以及以这些名字开头的命名空间(例如PHP\Classes)被保留用作语言内核使用,而不应该在用户空间的代码中使用。
定义命名空间
虽然任意合法的PHP代码都可以包含在命名空间中,但只有以下类型的代码受命名空间的影响,它们是:类(包括抽象类和traits)、接口、函数和常量。
命名空间通过关键字namespace 来声明。如果一个文件中包含命名空间,它必须在其它所有代码之前声明命名空间,除了一个以外:declare关键字。
namespace MyProject;const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */ }
定义子命名空间
namespace MyProject\Sub\Level;const CONNECT_OK = 1; //MyProject\Sub\Level\CONNECT_OKclass Connection { /* ... */ } //MyProject\Sub\Level\Connectionfunction connect() { /* ... */ } //MyProject\Sub\Level\connect
在同一个文件中定义多个命名空间
- 写法1
namespace MyProject;const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */ }namespace AnotherProject;const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */ }
- 写法2
namespace MyProject {const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */ }}namespace AnotherProject {const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */ }}
使用命名空间
- 非限定名称,或不包含前缀的类名称,例如
$a=new foo();
或foo::staticmethod();
。如果当前命名空间是currentnamespace
,foo 将被解析为currentnamespace\foo
。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,则 foo 会被解析为foo
。 警告:如果命名空间中的函数或常量未定义,则该非限定的函数名称或常量名称会被解析为全局函数名称或常量名称 - 限定名称,或包含前缀的名称,例如
$a = new subnamespace\foo();
或subnamespace\foo::staticmethod();
。如果当前的命名空间是currentnamespace
,则 foo 会被解析为currentnamespace\subnamespace\foo
。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,foo 会被解析为subnamespace\foo
- 完全限定名称,或包含了全局前缀操作符的名称,例如,
$a = new \currentnamespace\foo();
或\currentnamespace\foo::staticmethod();
。在这种情况下,foo 总是被解析为代码中的文字名(literal name)currentnamespace\foo
。
下面是示例:
# file1.php<?phpnamespace Foo\Bar\subnamespace;const FOO = 1;function foo() {}class foo{ static function staticmethod() {}}?># file2.php<?phpnamespace Foo\Bar;include 'file1.php';const FOO = 2;function foo() {}class foo{ static function staticmethod() {}}/* 非限定名称 */foo(); // 解析为 function Foo\Bar\foofoo::staticmethod(); // 解析为类 Foo\Bar\foo的静态方法staticmethodecho FOO; // 解析为 constant Foo\Bar\FOO/* 限定名称 */subnamespace\foo(); // 解析为函数 Foo\Bar\subnamespace\foosubnamespace\foo::staticmethod(); // 解析为类 Foo\Bar\subnamespace\foo , 以及类的方法 staticmethodecho subnamespace\FOO; // 解析为常量 Foo\Bar\subnamespace\FOO/* 完全限定名称 */\Foo\Bar\foo(); // 解析为函数 Foo\Bar\foo\Foo\Bar\foo::staticmethod(); // 解析为类 Foo\Bar\foo, 以及类的方法 staticmethodecho \Foo\Bar\FOO; // 解析为常量 Foo\Bar\FOO?>
注意访问任意全局类、函数或常量,都可以使用完全限定名称,例如 \strlen()
或 \Exception
或 \INI_ALL
。
<?phpnamespace Foo;function strlen() {}const INI_ALL = 3;class Exception {}$a = \strlen('hi'); // 调用全局函数strlen 2$b = \INI_ALL; // 访问全局常量 INI_ALL 7$c = new \Exception('error'); // 实例化全局类 Exception?>
命名空间和动态语言特征
example1.php:
<?phpclass classname{ function __construct() { echo __METHOD__,"\n"; }}function funcname(){ echo __FUNCTION__,"\n";}const constname = "global";$a = 'classname';$obj = new $a; // classname::__construct$b = 'funcname';$b(); // funcnameecho constant('constname'), "\n"; // global?>
<?phpnamespace namespacename;class classname{ function __construct() { echo __METHOD__,"\n"; }}function funcname(){ echo __FUNCTION__,"\n";}const constname = "namespaced";include 'example1.php';$a = 'classname';$obj = new $a; // classname::__construct$b = 'funcname';$b(); // prints funcnameecho constant('constname'), "\n"; // prints global/* note that if using double quotes, "\\namespacename\\classname" must be used */$a = '\namespacename\classname';$obj = new $a; // prints namespacename\classname::__construct$a = 'namespacename\classname';$obj = new $a; // also prints namespacename\classname::__construct$b = 'namespacename\funcname';$b(); // prints namespacename\funcname$b = '\namespacename\funcname';$b(); // also prints namespacename\funcnameecho constant('\namespacename\constname'), "\n"; // prints namespacedecho constant('namespacename\constname'), "\n"; // also prints namespaced?>
namespace关键字和NAMESPACE常量
PHP支持两种抽象的访问当前命名空间内部元素的方法,__NAMESPACE__
魔术常量和namespace
关键字。
常量__NAMESPACE__
的值是包含当前命名空间名称的字符串。在全局的,不包括在任何命名空间中的代码,它包含一个空的字符串。
常量 __NAMESPACE__
在动态创建名称时很有用,例如:
<?phpnamespace MyProject;function get($classname){ $a = __NAMESPACE__ . '\\' . $classname; return new $a;}?>
关键字 namespace
可用来显式访问当前命名空间或子命名空间中的元素。它等价于类中的 self
操作符。
<?phpnamespace MyProject;use blah\blah as mine;blah\mine(); // MyProject\blah\mine()namespace\blah\mine(); // MyProject\blah\mine()namespace\func(); // MyProject\func()namespace\sub\func(); // MyProject\sub\func()namespace\cname::method(); // MyProject\cname::method()$a = new namespace\sub\cname(); // MyProject\sub\cname$b = namespace\CONSTANT; // MyProject\CONSTANT?>
使用命名空间:别名/导入
为类名称使用别名,为接口使用别名,为命名空间名称使用别名,别名是通过操作符 use 来实现的
想了解更多编程学习,敬请关注php培训栏目!
The above is the detailed content of A little personal understanding of namespaces. For more information, please follow other related articles on the PHP Chinese website!

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft