如何制作全球可访问的对象 [英] How to make a globally accessible object
问题描述
我在Zend_Registry中发现了类似的东西,但是阅读它的代码我不明白调用一个静态函数可能会返回一个类的初始化实例...
我需要做类似的事情:
<?php
//index.php
$ obj = new myUsefulObject();
$ obj-> loadCfg(myFile.xml);
$ req = new HTTPRequest();
$ req-> filter(blablabla);
myappp :: registerClass(object,$ obj);
myappp :: registerClass(request,$ req);
$ c = new Controller();
$ c-> execute();
?>
这里我过滤了Request对象,我希望控制器能够达到已经过滤的请求。
<?php
类控制器
{
函数__construct()
{
$ this-> request = Application :: getResource(request); //这必须是过滤的var =(
)
}
?>
我不知道如何实现Application :: getResource(),我知道的唯一的事情就是它必须是一个静态方法,因为它不能与特定实例相关。 解决方案
除了静态方法外,PHP还具有静态属性:类属于本地属性,可以用来实现单例或者注册表:
class Registry {
private static $ _registry;
public static function registerResource($ key,$ object)
{
self :: $ _ registry [$ key] = $ object;
$ b $ public static function getResource($ key){
if(!isset(self :: $ _ registry [$ key]))
throw InvalidArgumentException(密钥$ key在注册表中不可用);
返回self :: $ _ registry [$ key];
}
}
Hi i have a little collection of classes some of which should be globally accessible.
I found something similar in Zend_Registry, but reading its code i cant understand how a call to a static function could return an initialized instance of a class...
i need to do something like:
<?php
//index.php
$obj = new myUsefulObject();
$obj->loadCfg("myFile.xml");
$req = new HTTPRequest();
$req->filter("blablabla");
myappp::registerClass("object",$obj);
myappp::registerClass("request",$req);
$c = new Controller();
$c->execute();
?>
Here i have filtered the Request object and i want the controller to be able to reach that already filtered request.
<?php
class Controller
{
function __construct()
{
$this->request = Application::getResource("request");//This must be the filtered var =(
}
}
?>
I don't know how to implement that Application::getResource(), the only thing i know is that it must be a static method because it can't be related to a specific instance.
Aside from static methods, PHP also has static properties: properties that are local to the class. This can be used to implement singletons, or indeed a Registry:
class Registry {
private static $_registry;
public static function registerResource($key, $object)
{
self::$_registry[$key] = $object;
}
public static function getResource($key) {
if(!isset(self::$_registry[$key]))
throw InvalidArgumentException("Key $key is not available in the registry");
return self::$_registry[$key];
}
}
这篇关于如何制作全球可访问的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!