When do/should I use __construct(), __get(), __set(), and __call() in PHP?

后端 未结 10 724
再見小時候
再見小時候 2020-12-05 08:16

A similar question discusses __construct, but I left it in my title for people searching who find this one.

Apparently, __get and __set take a parameter that is the

10条回答
  •  无人及你
    2020-12-05 08:59

    One good reason to use them would be in terms of a registry system (I think Zend Framework implements this as a Registry or Config class iirc), so you can do things like

    $conf = new Config();
    $conf->parent->child->grandchild = 'foo';
    

    Each of those properties is an automatically generated Config object, something akin to:

    function __get($key) {
        return new Config($key);
    }
    

    Obviously if $conf->parent already existed, the __get() method wouldn't be called, so to use this to generate new variables is a nice trick.

    Bear in mind this code I've just quoted isn't functionality, I just wrote it quickly for the sake of example.

提交回复
热议问题