note 27431 added to language.oop

From: Date: Thu, 05 Dec 2002 17:58:29 +0000
Subject: note 27431 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-40387@lists.php.net to get a copy of this message
I was dissappointed to find that PHP didn't support multiple constructs like Java does. In short in Java you can create multiple constructs all named the same, and based on the number of variables passed when creating a new object the appropriate construct is used to initialize the object. I stumbled on a way to do this using an array: class table { function table($aTableStyles) { // SET DEFAULT VALUES $this->titleBar = "off"; $this->titleBarBGColor = "#cccccc"; $this->titleBarFontFace = "#Times New Roman"; $this->titleBarFontColor = "#ffffff"; // OVERRIDE DEFAULT WITH USER SET VALUES while (list($key, $val) = each($aTableStyles) ) { $this->$key = $val; } } } // CREATE NEW OBJECT 1 // set values to send to constructor $aTableStyles1 = array( "titleBar" => "on" ) $newTable1 = new table($aTableStyles1); // CREATE NEW OBJECT 2 // set values to send to constructor $aTableStyles2 = array( $this->titleBarBGColor = "#cccccc"; $this->titleBarFontFace = "#Times New Roman"; $this->titleBarFontColor = "#ffffff"; ) $newTable2 = new table($aTableStyles2); -- Basically what I have done is created four class variables that hold default values. When the constructor is called you can choose to override the default values by passing any number of values in an associative array. The constructor simply loops through and replaces any of the default variables with user supplied ones. This way when a new object is created you can chose to override only a single value or all of them. This was very important in my table class because I had 30+ options the user could choose to override. Ron -- http://www.php.net/manual/en/language.oop.php http://master.php.net/manage/user-notes.php?action=edit+27431 http://master.php.net/manage/user-notes.php?action=delete+27431 http://master.php.net/manage/user-notes.php?action=reject+27431

« previous php.notes (#40387) next »