downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Object overloading Functions> <Examples
Last updated: Fri, 20 Nov 2009

view this page in

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->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->= array($val);
var_dump($o->a[0]->prop);

?>



Object overloading Functions> <Examples
Last updated: Fri, 20 Nov 2009
 
add a note add a note User Contributed Notes
Overloading a PHP class
scurvysquid at yahoo dot com
04-Jun-2009 12:43
Overloading is defining a method multiple times with different input parameters, then conditionally running whichever method matches the provided input.
It looks like the "overload" function just enables magic methods for a class, which can be used in implementing an extremely janky simulation of overloading.
Also, it seems that magic methods are enabled by default in php5 regardless of whether the overload function has been run on a class.
Anonymous
26-Mar-2009 05:48
You can't redeclare because PHP won't know which one to use. Use a default value and test conditionally instead such as

<?php
public function method($arg=false){
     if(
$arg==false){
        
//do something
    
} else {
        
//do something else
    
}
}
?>
ly dot sitthykun at yahoo dot com
22-Jan-2009 03:47
<?php
class Foo{
    public function
method(){
        echo
"call Method no paramater";
    }
    public function
method($par){
        echo
"call Method has a paramater";
    }

}

$foo = new Foo();

echo
$foo->method("param");]

?>

#output:
Fatal error: Cannot redeclare Foo::method() in class_overload.php on line 6

why?
we can not create the same method name.

Object overloading Functions> <Examples
Last updated: Fri, 20 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites