This article mainly introduces the object-oriented namespace of PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
Overview
Broadly speaking, namespace is a method of encapsulating physical objects;
For example, in the operating system, directories are used to group related files. For files in the directory, it plays the role of The role of namespaces.
In PHP, namespaces are used to create reusable code when writing class libraries or programs to solve the following problems:
1)用户编写的的代码,与PHP内部的类/常量/第三方类/函数/ 常量之间的名字冲突; 2)为很长的标识符名称,创建一个别名,提高代码的可读性;
Basic usage
Declared by key namespace
.
1)namespace MyPro1; /*内容*/ 2)namespace MyPro2{ /*内容*/ };
If a file contains a namespace, the namespace must be declared before all code.
<?php namespace A; function time() { echo '这是属于我的time方法'; } namespace B; function time() { echo '这是属于我的time方法2'; } time(); // namespace B time() \A\time(); // namespace A time() \B\time(); // namespace B time() echo \time(); // 系统的 time()
Sub namespace
namespace Father/Son;
<?php // 使用命名空间例子2 namespace A; function time() { echo '这是属于我的time方法'; } namespace B; function time() { echo '这是属于我的time方法2'; } time(); // namespace B time() \A\time(); // namespace A time() \B\time(); // namespace B time() echo \time(); // 系统的 time()
Related recommendations:
php object-oriented inheritance
php object-oriented overloading
The above is the detailed content of PHP object-oriented namespace. For more information, please follow other related articles on the PHP Chinese website!