2011-08-19 2 views
1

죄송합니다. 아직 OO를 처음 사용하셨습니다.설정 기본 기능 Param in Constructor

나는 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 클래스를 확장하고 사용자가 설정되지 않은 속성에 액세스하려고하면 호출되는 오프셋 메소드를 오버라이드 (override)하는 것입니다 생각합니다. 그럼 당신은 단지 당신이 거기에서 필요로하는 것을 돌려 주거나 설정할 수 있고, 그 구조를 잊어 버릴 수 있습니다.

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

그것은 추한하고 기능에 더 많은 옵션 변수가있는 경우 몇 가지 혼란의 원인이됩니다 ...

BTW, 출력은 다음과 같습니다

Method 1 says: 1 
M1 
Method 2 got param 5, and says: 2 
M2