从PHP命名空间中定义全局函数

时间:2021-10-02 23:45:04

Is it possible to define a global function from within a PHP namespace (within a file that has a namespace declaration)? If so, how?

是否可以在PHP名称空间内(在具有名称空间声明的文件中)定义全局函数?如果是这样,怎么样?

<?php
namespace my_module;

# bunch of namespaced functions
# ...
# then I want to define a global function my_module()
# that is an alias to my_module\mymodule()

1 个解决方案

#1


26  

It's possible but aside from being bad design, you will have to enclose your code within brackets for each namespace and won't be able to use namespace my_module; Instead it will have to be namespace my_module { ... }.

这是可能的,但除了糟糕的设计之外,你必须将代码括在每个命名空间的括号内,并且不能使用命名空间my_module;相反,它必须是名称空间my_module {...}。

Example:

namespace my_module {

    function module_function()
    {
        // code
    }
}

namespace {
    // global namespace.

    function my_module()
    {
        // call your namespaced code
    }
}

#1


26  

It's possible but aside from being bad design, you will have to enclose your code within brackets for each namespace and won't be able to use namespace my_module; Instead it will have to be namespace my_module { ... }.

这是可能的,但除了糟糕的设计之外,你必须将代码括在每个命名空间的括号内,并且不能使用命名空间my_module;相反,它必须是名称空间my_module {...}。

Example:

namespace my_module {

    function module_function()
    {
        // code
    }
}

namespace {
    // global namespace.

    function my_module()
    {
        // call your namespaced code
    }
}