Use __get() and __set() to dynamically access class fields in PHP

Description

The following code shows how to use __get() and __set() to dynamically access class fields.

Example


<?php//w  w w.  j  a  v  a 2 s. c o m

class Car {
  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;
    }
  }

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

$myCar = new Car();
$myCar->manufacturer = "Volkswagen";
$myCar->model = "Beetle";
$myCar->color = "red";
$myCar->engineSize = 1.8;
$myCar->otherColors = array( "green", "blue", "purple" );

echo "<p>My car's manufacturer is " . $myCar->manufacturer . ".</p>";
echo "<p>My car's engine size is " . $myCar->engineSize . ".</p>";
echo "<p>My car's fuel type is " . $myCar->fuelType . ".</p>";
echo "<h2>The \$myCar Object:</h2><pre>";
print_r( $myCar );
echo "</pre>";
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition