Detailed explanation of php namespace usage

*文
Release: 2023-03-18 18:56:01
Original
1808 people have browsed it

This article mainly introduces the usage of namespace use in PHP, and analyzes the definition and usage skills of namespace in PHP in the form of examples. Friends in need can refer to it. I hope to be helpful.

The details are as follows:

It feels a bit outdated to say this now, but I feel that not many people use namespace, probably because they are not used to it.

Class organizes functions one by one, and namespace can be understood as organizing classes, functions, etc. in an orderly manner. Personally, I think the main advantages of namespace are

First, it can better manage the code
Second, with more files, it can avoid duplicate names of classes and functions
Third, the code is readable Enhanced performance

1. Define namespace


namespace userCenter; //php代码 namespace userCenter\register; //php代码 namespace userCenter\login { //php代码 }
Copy after login

The namespace cannot be nested or declared multiple times in the same code (only will be recognized last time). However, you can define multiple namespaced codes in the same file. It is more appropriate to define a namespace for each file (it can be the same namespace).

2. Call namespace


\userCenter\register; //绝对调用 userCenter\login; //相对调用 use userCenter\register; //引用空间 use userCenter\register as reg; //引用空间并加别名
Copy after login

3. Example

login. class.php


"; } class login{ public function save(){ echo "login had saved
"; } } ?>
Copy after login

regist.class.php


##

"; } class regist{ public function save(){ echo "regist had saved
"; } } } ?>
Copy after login

test.php


save(); echo regist\check_username(); //相对调用 echo reg\check_username(); //别名调用 $regist = new reg\regist(); echo $regist->save();
Copy after login
Using use is better than absolute calling. It is like adding a prefix to class, function, etc., so that it looks clearer.

Related recommendations:

A brief analysis of namespace related concepts in php

PHP namespace and automatically loaded classes

Basics of using PHP namespace

The above is the detailed content of Detailed explanation of php namespace usage. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!