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

后端 未结 10 702
再見小時候
再見小時候 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 09:13

    Redefining __get and __set can be especially useful in core classes. For example if you didn't want your config to be overwritten accidentally but still wanted to get data from it:

    class Example
    {
        private $config = array('password' => 'pAsSwOrD');
        public function __get($name)
        {
            return $this->config[$name];
        }
    }
    
    0 讨论(0)
  • 2020-12-05 09:15

    I think it is bad for design you code. If you know and do a good design then you will not need to use the __set() and __get() within your code. Also reading your code is very important and if you are using studio (e.g. Zend studio), with __set() and __get() you can't see your class properties.

    0 讨论(0)
  • 2020-12-05 09:16

    __get(), __set(), and __call() are what PHP calls "magic methods" which is a moniker I think that is a bit silly - I think "hook" is a bit more apt. Anyway, I digress...

    The purpose of these is to provide execution cases for when datamembers (properties, or methods) that are not defined on the object are accessed, which can be used for all sorts of "clever" thinks like variable hiding, message forwarding, etc.

    There is a cost, however - a call that invokes these is around 10x slower than a call to defined datamembers.

    0 讨论(0)
  • 2020-12-05 09:16

    Probably not the cleanest design in the world but I had a situation where I had a lot of code that was referencing an instance variable in a class, i.e.:

    $obj->value = 'blah';
    echo $obj->value;
    

    but then later, I wanted to do something special when "value" was set under certain circumstances so I renamed the value variable and implemented __set() and __get() with the changes I needed.

    The rest of the code didn't know the difference.

    0 讨论(0)
提交回复
热议问题