note 53419 deleted from language.oop5.decon by felipe

From: Date: Mon, 24 Mar 2008 22:45:57 +0000
Subject: note 53419 deleted from language.oop5.decon by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-137511@lists.php.net to get a copy of this message
Note Submitter: shakeel at nxb dot com dot pk ---- In order to make constructor overloading in PHP5, we have to make a function __construct and inside from that's constructor, use func_num_args to get the total numbers of arguments supplied to the constructor and then do appropriate work or call some other function. The value of any argument can be acceessed by using func_get_arg($index) function. This is illustrated in the following Example. <?php class Overload { private $var1; private $var2; # constructor which acts as a overloaded constructors public function __construct() { $num_args=func_num_args(); switch ($num_args) { case '0': // Do something # set zero in both instance variables. if no argument is #supplied $this->var1 = $this->var2 =0; break; case '1': # get value of the argument $arg1=func_get_arg(0); // Do something else; /* asigned ist arg. to ist instance variable and Zero in the 2nd instance variable or any other initializing value. because only one argument is supplid. */ $this->var1 = $arg1; $this->var2 = 0; break; case '2': // get value of both arguments $arg1=func_get_arg(0); $arg2=func_get_arg(1); // Do something else; $this->var1 = $arg1; $this->var2 = $arg2; break; } // end of switch statement } // end of function __construct // function to display the values of instance variables function display() { echo "var1: $this->var1 <br>"; echo "var2: $this->var2 <br><br>"; }// end of function display }// end of class // create 3 objects with different no. of arguments $over = new Overload(); $over1 = new Overload(5); $over2 = new Overload(5,10); // call display function with all 3 objects. $over->display(); $over1->display(); $over2->display(); ?> output: var1: 0 var2: 0 var1: 5 var2: 0 var1: 5 var2: 10

« previous php.notes (#137511) next »