downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  

<Predefined ConstantsObject overloading Functions>
Last updated: Thu, 26 Jun 2008

Examples

Some simple examples on using the overload() function:

Example #1 Overloading a PHP class

<?php

class OO {
   var
$a = 111;
   var
$elem = array('b' => 9, 'c' => 42);

  
// Callback method for getting a property
  
function __get($prop_name, &$prop_value)
   {
       if (isset(
$this->elem[$prop_name])) {
          
$prop_value = $this->elem[$prop_name];
           return
true;
       } else {
           return
false;
       }
   }

  
// Callback method for setting a property
  
function __set($prop_name, $prop_value)
   {
      
$this->elem[$prop_name] = $prop_value;
       return
true;
   }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo
"\$o->a: $o->a\n"; // print: $o->a: 111
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:

// add a new item to the $elem array in OO
$o->x = 56;

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>



add a noteadd a note User Contributed Notes
Examples
There are no user contributed notes for this page.




<Predefined ConstantsObject overloading Functions>
Last updated: Thu, 26 Jun 2008
show source | credits | sitemap | contact | advertising | mirror sites
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://phpbuilder.com/
Last updated: Tue Nov 1 20:20:59 2005 EST
Columns / Articles | Tips / Quickies | News | News Linking and RSS Feeds | Shared Code Library
Mail Archives | Support / Discussion Forums | Get Started! Links | Contribute! | Docs