好好爱自己!

php 命名空间

参考:http://php.net/manual/en/language.namespaces.definitionmultiple.php

http://jingyan.baidu.com/article/f3e34a12a8dfc2f5eb6535ce.html

php 的命名空间,defining mutiple namespaces in the same file.

1. 多个命名空间写法要统一, 要么 namespace Ysr; 要么 namespace Ysr{}

It is strongly discouraged as a coding practice to combine multiple namespaces into the same file.

The primary use case is to combine multiple PHP scripts into the same file.

2. 好的编码习惯并不建议将多个命名空间写在一个脚本文件当中。 将多个命名空间写在同一个脚本文件当中的做法一般只是当要 “include” 或者 "require" 其他文件进来的时候,这个时候会出现一个脚本文件中 有多个命名空间。

 

3. 全局的代码 包含在 namespace 什么的代码块中, namespace 后面不用出现命名空间的名字。

To combine global non-namespaced code with namespaced code, only bracketed syntax is supported. Global code should be encased in a namespace statement with no namespace name as in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
namespace MyProject\YSR\haha{
    const CONNECT_OK = 1;
    function var_dump(){
        echo 'ysr';
    }
}
 
 
 
namespace {
    use MyProject\YSR\haha;
    $a = 2;
    haha\var_dump($a);
}
 
namespace AnotherProject{
 
    const CONNECT_OK = 1;
    class Connection { /* ... */ }
    function connect() { /* ... */  }
}

  4. 通过命名空间来调用函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//food.php
 
<?php
namespace Food;
 
require ('Apple.php');
require('Orange.php');
 
use Apples;
use Oranges;
 
Apples\eat();
Oranges\eat();
?>
 
    //Apple.php
    <?php
namespace Apples;
 
function eat()
{
    echo "eat apple";
}
?>
 
    //Orange.php
    <?php
namespace Oranges;
 
function eat()
{
    echo "eat Orange";
}
?>

  -------------------------------------------------------------------------------------------------------------

5. 命名空间的别名运用。

命名空间的别名,主要是用来正对命名空间比较长的情况, 还有就是命名空间导入类,函数和常量是不能用命名空间导入的(函数好像可以导入,这个有点疑问!!)。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
 
 
namespace MyProject\YSR\haha{
    const CONNECT_OK = 1;
    function var_dump(){
        echo 'ysr';
    }
}
 
 
 
namespace {
    use MyProject\YSR\haha;
    use AnotherProject\zzz;
    $a = 2;
    var_dump( zzz\CONNECT_OK); //报错,
//    var_dump( new zzz\Connection());
//    var_dump( zzz\connect());
}
 
namespace AnotherProject\zzz{
 
    const CONNECT_OK = 1;
    class Connection {
        public function __construct()
        {
            echo "come in";
        }
    }
    function connect() {
        echo "AnotherProject funciton ysr ";
    }
}

  

 

posted @   立志做一个好的程序员  阅读(298)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示