PHP - Object Overloading with -get(), -set(), and -call()

Introduction

PHP can intercept attempts to read or write an object's properties, or call its methods.

PHP can create three "magic" methods that you can use to intercept property and method accesses:

Method Description
__get() called whenever the calling code attempts to read an invisible property of the object
__set() called whenever the calling code attempts to write to an invisible property of the object
__call()called whenever the calling code attempts to call an invisible method of the object

In this context, invisible means that the property or method isn't visible to the calling code.

Usually this means that the property or method simply doesn't exist in the class.

It can also mean that the property or method is either private or protected, and hence isn't accessible to code outside the class.

To intercept attempts to read an invisible property, you create a method called __get() within your class.

Your __get() method should expect a single argument: the name of the requested property.

It should then return a value; this value in turn gets passed back to the calling code as the retrieved property value.

Demo

<?php
            class Truck {
              public function __get($propertyName) {
                echo"The value of'$propertyName'was requested \n";
                return"blue";
              }//from  w w  w . j a  va 2 s . c  o  m
            }

            $truck = new Truck;
            $x = $truck->color; // Displays"The value of'color'was requested"
            echo"The Truck's color is $x \n"; // Displays"The Truck's color is blue"
            $x = $truck->speed; 
            echo"$x \n"; 

?>

Result

Here, the Truck class contains no actual properties, but it does contain a __get() method.

This method displays the value of the requested property name, and returns the value "blue".

Then the code creates a new Truck object, and attempts to retrieve the nonexistent property $truck->color, storing the result in a new variable, $x.

Doing this triggers the Truck object's __get() method, which displays the requested property name ("color") and returns the literal string "blue".

This string is then passed back to the calling code and stored in $x.

Related Topic