PHP全局命名空间功能 [英] PHP Global Namespace Function

查看:121
本文介绍了PHP全局命名空间功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我可以使用myFunc()而不是\myFunc()从另一个名称空间访问全局名称空间中的函数.如果无法在当前名称空间中解析myFunc,PHP将自动回退到全局名称空间.

In PHP, I can access a function in global namespace from another namespace using myFunc(), instead of \myFunc(). PHP Will automatically fallback to the global namespace, if myFunc cannot be resolved in the current namespace.

推荐哪种方式? \myFunc()myFunc()?

推荐答案

如果要实现某种多态性或完全改变函数的逻辑,第二个选项更好.像这样的东西.

Second option is better if you want to implement some kind of polymorphism or to completely change function's logic. Something like this.

namespace Nkamm;

// like a PHP6
function strstr($needle, $haystack)
{
    return \strstr($haystack, $needle);
}

var_dump(strstr('t', 'Long test'));

结果:

string(4) "test"

但是我不想做这样的重载",因为那样会造成混乱(直到它们在项目中得到严格记录).因此,没有必要覆盖现有功能.

But I would not like to do such "overloads" because that will cause the mess (until they are strictly documented in project). Hence there is no sense to overwrite existing functions.

总结:将函数保留在名称空间中,使用不带反斜杠的全局函数.

Summing up: keep your functions in your namespace, use global functions without any backslashes.

这篇关于PHP全局命名空间功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆