2010-08-11 3 views
0

그래서 전달되지 않으면 기본값을 설정하는 클래스가 있습니다. 예를 들어, $ options라는 배열을 전달할 수 있습니다.php - 키가 배열에 존재하면 var를 설정하고, 그렇지 않으면 default로 설정합니다.

function new_score($options) 
{ 

} 

그리고 그 VAR의 이름을 가진 키가 $ 옵션 배열에 존재하지 않는 경우 나 기본에 VAR을 설정할 수있는 다른 기능을 가지고 싶습니다;

함수 정의는 다음과 같을 수 있습니다 :

function _set(&$key, $options, $default) 
{ 
} 

나는 array_key_exists()이 알고, 그리고 내가 종류의 변수 이름에 액세스 할 수있는 방법을 찾고 있어요 같아요.

$apple = 'orange'; 

가 어떻게 문자열 '사과'를 얻을 수 있습니다, 그래서 그 키도 찾아보실 수 있습니다 : 예를 들어

? _set() 함수를 사용하여 $ key, $ var, $ options 및 $ default를 찾을 수는 있지만 필자는이를 추상화하려고합니다.

$defaults = array('foo' => 'bar', 'other' => 'default value'); 
$array = $array + $defaults; 

답변

3
function method($options) 
{ 
    //First, set an array of defaults: 
    $defaults = array("something" => "default value", 
        "something_else" => "another default"); 

    //Second, merge the defaults with the $options received: 
    $options = array_merge($defaults, $options); 

    //Now you have an array with the received values or defaults if value not received. 
    echo($options["something"]); 

    //If you wish, you can import variables into local scope with "extract()" 
    //but it's better not to do this... 
    extract($options); 
    echo($something); 
} 

: 전체 배열로,

$key = isset($array['foo']) ? $array['foo'] : 'default'; 

또는 : 삼항 연산자를 사용하여 한 번에

하나 :

+0

기억하십시오 : $ defaults를 먼저 array_merge()로 전달하십시오 : $ options = array_merge ($ defaults, $ options); 배열 조합을 사용하는 경우 마지막에 넣으십시오. $ options = $ options + $ defaults; –

1

이 방법에 대해 :

class Configurable 
{ 
private static $defaults = array (
    'propertyOne'=>'defaultOne', 
    'propertyTwo'=>'defaultTwo' 
); 

private $options; 

public function __construct ($options) 
{ 
    $this->options = array_merge (self::$defaults, $options); 
} 
} 

the documentation for array_merge에서 :

입력 배열은 같은 문자열 키, 해당 키의 의지에 대한 다음 나중에 값이있는 경우 이전 개를 덮어 씁니다.

+0

+1. 이 답변은 OOP 기능이 훨씬 뛰어납니다. –

관련 문제