0

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.

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::get_config('key').

Obviously with namespacing, I would need to call \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?

4

3 回答 3

0

在脚本顶部添加

use TheNameSpace\App as MyApp

例如。然后你可以像这样使用它

app = new MyApp();

在你的脚本中。当然你不需要在这里使用别名。只是

use TheNameSpace\App
app = new App();

也会起作用。

实现这个的全局类是不好的风格,你不应该这样做:

class MyApp extends TheNameSpace\App { }

....
myApp = new MyApp();
于 2013-02-20T15:56:26.950 回答
0
namespace Foo;
use Bar;

那么你不必做\Bar\fn

所以在你的情况下:

namspace Foo;
use TheNameSpace\App;

App::get_config('blah')
于 2013-02-20T15:56:47.980 回答
0

阅读 php 手册中关于使用/别名命名空间的部分。

http://www.php.net/manual/en/language.namespaces.importing.php

您可以使用“use”排除命名空间。你可以随意命名它。

use TheNamespace\App as App //You can name it anything here
App:config('key');
于 2013-02-20T15:57:23.063 回答