Home >Backend Development >PHP Tutorial >PHP object-oriented namespace

PHP object-oriented namespace

不言
不言Original
2018-06-06 10:15:351367browse

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{
    /*内容*/
};

Note:

If a file contains a namespace, the namespace must be declared before all code.

Example

<?php

namespace A;

function time()
{
    echo &#39;这是属于我的time方法&#39;;
}


namespace B;

function time()
{
    echo &#39;这是属于我的time方法2&#39;;
}

time();  // namespace B time()

\A\time();  // namespace A time()

\B\time();  // namespace B time()

echo \time();  // 系统的 time()

Sub namespace

Usage

namespace Father/Son;

Example

<?php
// 使用命名空间例子2

namespace A;

function time()
{
    echo &#39;这是属于我的time方法&#39;;
}


namespace B;

function time()
{
    echo &#39;这是属于我的time方法2&#39;;
}
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!

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