2011-08-19 265 views
1

对不起,对面向对象还是一个新东西。在构造函数中设置默认函数参数

我正在使用CodeIgniter,但这个问题基本上只是PHP OO。

我有为数众多的做类似的事情函数的类文件:

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'];   
     } 

现在,而不是这样做,在每次方法在这个类中,我可以在构造函数中设置呢?所以我仍然可以明确地传递$ the_id,以覆盖它,否则它总是默认为$this->member['the_id'];

这样做的最优雅方式是什么?

回答

0

如何将所有初始化数据作为数组传递给构造函数?

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 
} 
0

我觉得最优雅的方式将是扩展的ArrayObject的类和覆盖偏移方法,如果您尝试访问未设置属性时调用。然后,您可以返回或设置您需要的内容并忘记构造。

-1

,你可以这样做:

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>'; 
当然

它的丑陋,并会给您造成一定的混乱,如果你有功能的更多可选变量...

顺便说一句,输出为:

Method 1 says: 1 
M1 
Method 2 got param 5, and says: 2 
M2 
相关问题