Skip to content

Do PHP objects use getters and setters internally?

by Andrew McCombe on July 26th, 2011

I just came across something that made me wonder wether a PHP object uses the magic __get() and __set() methods inside the object itself.  I wrote the following code to test:

<?php 
class Test {
        public function __construct()
       {
            $this->name = 'Andrew';
        }
 
        public function __get($name) {
                echo '__get: ' . $name . "\n";
        }
 
        public function __set($name, $value) {
                echo '__set: ' . $name . ', ' . $value . "\n";
        }
}
 
$name = new Test();
$name->name = 'Amy';
 
echo $name->name;

Here’s the output:

andrew@adele:~$ php check_getters.php
__set: name, Andrew
__set: name, Amy
__get: name

Answer: Yes they do!

From → PHP

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS