Home  >  Article  >  Backend Development  >  what is php namespace

what is php namespace

(*-*)浩
(*-*)浩Original
2019-09-21 15:11:314098browse

What is a namespace?

what is php namespace

In a broad sense, a namespace is a way of encapsulating things. This abstract concept can be found in many places.

For example, in the operating system, directories are used to group related files. For the files in the directory, it plays the role of a namespace. (Recommended learning: PHP Programming from Beginner to Master)

For a specific example, the file foo.txt can exist in the directories /home/greg and /home/other at the same time, but in Two foo.txt files cannot exist in the same directory.

In addition, when accessing the foo.txt file outside the directory /home/greg, we must put the directory name and directory separator before the file name to get /home/greg/foo.txt. The application of this principle to the field of programming is the concept of namespace.

In PHP, namespaces are used to solve two types of problems encountered when creating reusable code such as classes or functions when writing class libraries or applications:

Name conflicts between user-written code and PHP internal classes/functions/constants or third-party classes/functions/constants.

Create an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem) to improve the readability of the source code.

PHP namespaces provide a way to group related classes, functions, and constants together. The following is an example illustrating PHP namespace syntax:

Namespace syntax example

<?php
namespace my\name; 

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass;

$a = strlen(&#39;hi&#39;); 

$d = namespace\MYCONST; 

$d = __NAMESPACE__ . &#39;\MYCONST&#39;;
echo constant($d); 
?>

Note:

named The PHP or php namespaces, and namespaces starting with these names (such as PHP\Classes) are reserved for language kernel use and should not be used in user space code.

The above is the detailed content of what is php 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