[英]PHP PSR-0 Static Class
I'm trying to rewrite an OO PHP site (that loosely follows an MVC structure) so it uses namespaces - and want to follow PSR-0. 我正在尝试重写OO PHP网站(大致遵循MVC结构),因此它使用名称空间-并希望遵循PSR-0。
In the current site I have a class (called APP) which is full of static methods that I call all over the place to handle things such as getting config data eg; 在当前站点中,我有一个类(称为APP),该类充满了静态方法,我在各处调用这些方法来处理诸如获取配置数据之类的事情。
APP::get_config('key')
. APP::get_config('key')
Obviously with namespacing, I would need to call \\TheNameSpace\\App::get_config('key')
. 显然,使用命名空间,我需要调用
\\TheNameSpace\\App::get_config('key')
。 I use this class frequently, so want to avoid having to prefix the namespace every time I use it. 我经常使用此类,因此要避免每次使用时都必须为命名空间添加前缀。 I do call methods in it from within other classes, which would usually be under a sub-namespace - so changing the namespace at the top of the file won't really work.
我确实从其他类中调用方法,这些类通常位于子命名空间下-因此更改文件顶部的命名空间将无法真正起作用。
So, I guess my question is, what is the easiest way to have a 'global' class with methods that I can call anywhere without having to prefix with the namespace each time? 因此,我想我的问题是,拥有一个“全局”类的最简单方法是使用可以在任何地方调用而不必每次都以名称空间为前缀的方法?
At top of your scripts add 在脚本顶部添加
use TheNameSpace\App as MyApp
for example. 例如。 You can then use it like
然后,您可以像
app = new MyApp();
in your scripts. 在您的脚本中。 Of course you needn't to use an alias here.
当然,您无需在此处使用别名。 Just
只是
use TheNameSpace\App
app = new App();
will work, too. 也会起作用。
A global class that's implementing this one is bad style and you shouldn't do it like this: 实现这一目标的全局类是不好的风格,您不应该这样:
class MyApp extends TheNameSpace\App { }
....
myApp = new MyApp();
namespace Foo;
use Bar;
Then you do not have to do \\Bar\\fn
然后,您不必执行
\\Bar\\fn
So in your case: 因此,在您的情况下:
namspace Foo;
use TheNameSpace\App;
App::get_config('blah')
Read the section in the php manual on using/aliasing namespaces. 阅读php手册中有关使用/别名空间的部分。
http://www.php.net/manual/en/language.namespaces.importing.php http://www.php.net/manual/zh/language.namespaces.importing.php
You can exclude the namespace by using "use". 您可以使用“ use”排除名称空间。 You can name it whatever you want.
您可以随意命名。
use TheNamespace\App as App //You can name it anything here
App:config('key');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.