note 53419 added to language.oop5.decon

From: Date: Wed, 01 Jun 2005 05:57:38 +0000
Subject: note 53419 added to language.oop5.decon
Groups: php.notes 
Request: Send a blank email to php-notes+get-89717@lists.php.net to get a copy of this message
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 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.decon.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+53419 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53419&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53419&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53419&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53419&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53419&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+53419&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#89717) next »