Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

oop - PHP Registry Pattern

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];
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";

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

To retrieve a value...

$foo = $registry->foo;

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

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...