Setting Default Function Param in Constructor
Sorry, still new to OO.
I'm working with CodeIgniter but this question is basically just PHP OO.
I have a class file with a bunch of functions that do a 开发者_JAVA技巧similar thing:
function blah_method($the_id=null)
{
// if no the_id set, set it to user's default
if(!isset($the_id)){
$the_id = $this->member['the_id'];
}
Now, Instead of doing that on every method in this class, can I set this up in the constructor? so that I can still pass in $the_id explicitly, to overide it but otherwise it always just defaults to $this->member['the_id'];
What's the most elegant way of doing that?
How about passing all your initialising data to the constructor as an array?
public function __construct(array $settings) {
// if 'the_id' has not been passed default to class property.
$the_id = isset($settings['the_id']) ? $settings['the_id'] : $this->member['the_id'];
// etc
}
I think the most elegant way would be to extend the arrayobject class and to override the offset method which is called if you try to access a property which is not set. Then you can just return or set what you need there and forget the construct.
you can do this:
class A {
private $id = null;
public function __construct($this_id=null){
$this->id = $this_id;
}
public function _method1(){
echo 'Method 1 says: ' . $this->id . '<br/>';
return "M1";
}
public function _method2($param){
echo 'Method 2 got param '.$param.', and says: ' . $this->id . '<br/>';
return "M2";
}
public function __call($name, $args){
if (count($args) > 0) {
$this->id = $args[0];
array_shift($args);
}
return (count($args) > 0)
? call_user_func_array(array($this, '_'.$name), $args)
: call_user_func(array($this, '_'.$name));
}
}
$a = new A(1);
echo $a->method1() . '<br>';
echo $a->method2(2,5) . '<br>';
of course it's ugly and will cause you some mess if you have more optional variables in the functions...
btw, the output is:
Method 1 says: 1
M1
Method 2 got param 5, and says: 2
M2
精彩评论