PHP object-oriented namespace

不言
Release: 2023-03-29 22:32:01
Original
1350 people have browsed it

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)为很长的标识符名称,创建一个别名,提高代码的可读性;
Copy after login

Basic usage

Declared by key namespace.

1)namespace MyPro1;
     /*内容*/


2)namespace MyPro2{
    /*内容*/
};
Copy after login

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()
Copy after login

Sub namespace

Usage

namespace Father/Son;
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template