When we look at Javascript frameworks such as Dojo, Mootools, jQuery, JS Prototype, etc., we see that parameters are often defined using such an array:
dosomething('mainsetting',{duration:3,allowothers:true,astring:'hello'});
Is it wrong to use this idea when writing a PHP class?
Example:
class Hello { private $message = ''; private $person = ''; public function __construct($options) { if(isset($options['message'])) $this->message = $message; if(isset($options['person'])) $this->person = $person; } public function talk() { echo $this->person . ' says: ' . $this->message; } }
Regular approach:
class Hello { private $message = ''; private $person = ''; public function __construct() {} public function setmessage($message) { $this->message = $message; } public function setperson($person) { $this->person = $person; } public function talk() { echo $this->person . ' says: ' . $this->message; } }
The advantage in the first example is that you can pass as many parameters as you want, and the class will retrieve only those that it needs.
For example, this may be convenient when extracting parameters from a JSON file:
$options = json_decode($options); $hello = new Hello($options);
Here is how I do it:
$options = json_decode($options); $hello = new Hello(); if(isset($options['message'])) $hello->setmessage($options['message']); if(isset($options['person'])) $hello->setperson($options['person']);
Is there a name for this template, and do you think this is bad practice?
I left validation, etc. in the examples to make it simple.