Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php __get and __set magic methods - why do we need those here?

On Zend Quick Start Guide here http://framework.zend.com/manual/en/learning.quickstart.create-model.html we can see:

class Application_Model_Guestbook
{
    protected $_comment;
    protected $_created;
    protected $_email;
    protected $_id;

    public function __set($name, $value);
    public function __get($name);


    public function setComment($text);
    public function getComment();
...

I normally create my getters and setters without any magic method. I've seen this on the quick guide, and I don't understand why may we need this.

Can anyone help me out?

Thanks a lot

like image 767
MEM Avatar asked Apr 25 '11 16:04

MEM


People also ask

Why we use magic methods in PHP?

Magic methods in PHP are special methods that are aimed to perform certain tasks. These methods are named with double underscore (__) as prefix. All these function names are reserved and can't be used for any purpose other than associated magical functionality. Magical method in a class must be declared public.

What is the purpose of the magic method?

Magic methods in Python are the special methods that start and end with the double underscores. They are also called dunder methods. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action.

What is get and set method in PHP?

Getters and setters are methods used to define or retrieve the values of variables, normally private ones. Just as the name suggests, a getter method is a technique that gets or recovers the value of an object. Also, a setter method is a technique that sets the value of an object.

What is __ get in PHP?

PHP calls the __get() method automatically when you access a non-existing or inaccessible property. PHP calls the __set() method automatically when you assign a value to a non-existing or inaccessible property.


1 Answers

You (usually) never call __set or __get directly. $foo->bar will call $foo->__get('bar') automatically if bar is not visible and __get exists.

In the tutorial you've linked to, the getter and setter get set up to automatically call the appropriate individual get/set functions. So $foo->comment = 'bar' will indirectly call $foo->setComment('bar'). This isn't necessary... it's only a convenience.

In other cases, __get can be useful to create what looks like a read-only variable.

like image 163
Matthew Avatar answered Oct 15 '22 11:10

Matthew