Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__get is not called if __set is not called, however code works?

Here is my code:

<?php

class SampleClass {

    public function __get($name){
        echo "get called";
        echo $name;
    }

    public function __set($name, $value) {
        echo "set called";
    }

}

?>

And my index file:

$object = new SampleClass();
$object->color = "black";
echo $object->color;

If I run this code as it is, here is the output:

set calledget calledcolor

However if I comment out

public function __set($name, $value) {
    echo "set called";
}

the part above (only this part), then the output will be:

black

So what happened here?

like image 632
Koray Tugay Avatar asked Jan 28 '13 21:01

Koray Tugay


2 Answers

__get will only be called is no property exists. By removing __set, you create a property when setting, so instead of calling __get, php just returns the property.

A simple way to think about it is that __get and __set are error handlers - They kick in, when php can't otherwise honor your request.

like image 157
troelskn Avatar answered Sep 23 '22 23:09

troelskn


This is an explanation of what is happening. In your first example. You never stored the value within the object, nor did a declared property exist. This, echo $object->color; never actually does anything as nothing is returned from __get.

In your second example, you assigned a value to a property in your object. Since you did not declare the property in your object, it gets created by default as public. Since its public, __get is never called when accessing it.

like image 31
datasage Avatar answered Sep 22 '22 23:09

datasage