2011-12-09 4 views
0

다음은 클래스의 예입니다. 생성자에서 정의 된 기본 옵션이 있으며 제공되는 옵션으로 대체하려고합니다.Array가 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 &$... ])

배열을 돌려줍니다.

관련 문제