在构造函数中设置默认函数参数

时间:2011-08-19 00:46:21

标签: php oop codeigniter

对不起,还是OO的新手。

我正在使用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'];

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

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

我认为最优雅的方法是扩展arrayobject类并覆盖在尝试访问未设置的属性时调用的offset方法。然后你可以返回或设置你需要的东西而忘记构造。

答案 2 :(得分:-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
相关问题