PHP注册表模式 [英] PHP Registry Pattern

查看:143
本文介绍了PHP注册表模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在网络上的几个地方找到了这段代码,甚至在Stack Overflow上也找到了,但是我不能把头包围。我知道它是做什么的,但我不知道它甚至与实例一样。基本上它是存储值,但我不知道如何向注册表添加值。有人可以尝试解释这段代码如何工作,我如何设置和检索这些代码?

I've found the piece of code below in several places around the web and even here on Stack Overflow, but I just can't wrap my head around it. I know what it does, but I don't know how it does it even with the examples. Basically it's storing values, but I don't know how I add values to the registry. Can someone please try to explain how this code works, both how I set and retrieve values from it?

class Registry {

    private $vars = array();

    public function __set($key, $val) {
        $this->vars[$key] = $val;
    }

    public function __get($key) {
        return $this->vars[$key];
    }
}


推荐答案

使用PHP黑客入侵属性重载来添加条目并检索私人 $ vars 数组中的条目。

It's using PHP's hacked on property overloading to add entries to and retrieve entries from the private $vars array.

要添加属性,您将使用...

To add a property, you would use...

$registry = new Registry;
$registry->foo = "foo";

在内部,这将添加一个 foo 通过魔术 __ set 方法到 $ vars 数组,并使用字符串值foo。

Internally, this would add a foo key to the $vars array with string value "foo" via the magic __set method.

要检索一个值...

$foo = $registry->foo;

在内部,这将检索 foo 条目通过魔术 __获取方法从 $ vars 数组。

Internally, this would retrieve the foo entry from the $vars array via the magic __get method.

__ get 方法应该真的检查不存在的条目并处理这样的事情。代码原样将触发未定义索引的 E_NOTICE 错误。

The __get method should really be checking for non-existent entries and handle such things. The code as-is will trigger an E_NOTICE error for an undefined index.

更好的版本可能是



A better version might be

public function __get($key)
{
    if (array_key_exists($key, $this->vars)) {
        return $this->vars[$key];
    }

    // key does not exist, either return a default
    return null;

    // or throw an exception
    throw new OutOfBoundsException($key);
}

这篇关于PHP注册表模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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