PHP - Implementing __set() method

Introduction

To catch an attempt to set an invisible property to a value, use needs two parameters: the property name and the value to set it to.

It does not need to return a value:

public function __set($propertyName, $propertyValue) {
    // (do whatever needs to be done to set the property value)
}

The following example shows how __get() and __set() can be used to store "nonexistent" properties in a private array.

This technique is useful for creating classes that need to hold arbitrary data.

Demo

<?php
        class Truck {
         public $manufacturer;
         public $model;
         public $color;
         private $_extraData = array();

         public function __get($propertyName) {
           if (array_key_exists($propertyName, $this->_extraData)) {
             return $this->_extraData[$propertyName];
           } else {
             return null;/* ww  w  .  ja v  a2  s .co  m*/
           }
         }

         public function __set($propertyName, $propertyValue) {
           $this->_extraData[$propertyName] = $propertyValue;
         }
        }

        $myTruck = new Truck();
        $myTruck->manufacturer ="Niu";
        $myTruck->model ="usa";
        $myTruck->color ="red";
        $myTruck->engineSize = 1.8;
        $myTruck->otherColors = array("green","blue","purple");
        echo "My Truck's manufacturer is". $myTruck->manufacturer.".\n";
        echo "My Truck's engine size is". $myTruck->engineSize.".\n";
        echo "My Truck's fuel type is". $myTruck->fuelType.".\n";
        echo "The \$myTruck Object:";
        print_r($myTruck);
?>

Result

Related Topic