PHP - Implementing __set() method


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.


        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;/*  w ww  . j a  v  a2  s . c  o 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:";


Related Topic