Use dynamic properties in PHP

Description

The following code shows how to use dynamic properties.

Example


//from  w  w w. j a v a2s  . co m
<?php
  class Overloader
  {
    private $properties = array();

    function __get($property_name)
    {
      if(isset($this->properties[$property_name]))
      {
        return($this->properties[$property_name]);
      }
      else
      {
        return(NULL);
      }
    }

    function __set($property_name, $value)
    {
      $this->properties[$property_name] = $value;
    }

    function __call($function_name, $args)
    {
      print("Invoking $function_name()<br>\n");
      print("Arguments: ");
      print_r($args);
      return(TRUE);
    }
  }

  $o = new Overloader();

  //invoke __set()
  $o->dynaProp = "Dynamic Content";

  //invoke __get()
  print($o->dynaProp . "<br>\n");

  //invoke __call()
  $o->dynaMethod("Leon", "Zeev");
?>

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