2011-12-09 59 views
0

这是我的类的一个示例,我在构造函数中定义了默认选项,我想用提供的任何选项替换它们。在构造函数中替换PHP

class Class{ 
    private $options; 

    function __construct($options=null){ 
    $this->options = array('option1'=>'value', 'option2'=>'value', ...); 
    array_replace(_recursive)($this->options,$options); 
    } 

    function showOpts(){ 
    print_r($this->options); 
    } 
} 

$opt = array('newOpt'=>value ..); 
$c = new Class($opt); 
$c->showOpts(); 

当我打印选项的内容我得到的默认值没有任何更换。 我在做什么错?

+1

你有一个错字(array_replace(_recursive)应该是array_replace_recursive') –

回答

2

因为array_replace_recursive返回结果数组。

您应其结果分配被$ this->选项

2

你忘了设置与阵列方法结果变量的选项。

function __construct($options=null){ 
    $this->options = array('option1'=>'value', 'option2'=>'value', ...); 
    $this->options = array_replace_recursive($this->options,$options); 
} 
1

防弹:

function __construct($options = array()){ 
    $this->options = array('option1'=>'value', 'option2'=>'value', ...); 
    $new_options = array_replace($this->options, $options); 
    if ($new_options) 
     $this->options = $new_options; 
    } 

函数定义:

array array_replace (array &$array , array &$array1 [, array &$... ])

如果发生错误,则返回一个数组,或NULL。