2011-08-30 4 views
0

, 나는이 같은 객체가 있습니다PHP에서 모든 세터 것들을 할 배열을 작성하는 방법? 예를 들어

class myObj{ 
private $a; 
private $b; 

//getter , setter 

} 

을 그리고 나는 같은 것을 할 싶습니다

$myObj = initWitharray(array('a'=> 'myavalue', 
          'b'=> 'mybvalue')); 

을 그리고 myObj로 모든 값과 B 값을가집니다. 그렇게하려면 어떻게해야합니까? 고맙습니다.

+1

'myObj'의 private 변수에 액세스해야하기 때문에이 init 메소드는 실제로 클래스의 멤버 여야합니다. – NullUserException

+0

배열과 같이 객체를 사용하려면 PHP 기본 제공 Iterator 인터페이스를 사용하는 것이 좋습니다. http://www.php.net/manual/en/class.iterator.php –

답변

1

제안 :

<?php 

class myObj { 

    private $a; 
    private $b; 

    public function initWithArray(array $arr) { 
     foreach ($arr as $k => $v) { 
      $this->$k = $v; 
     } 
     return $this; 
    } 

    public function get($name) { 
     return $this->$name; 
    } 

} 

// usage 
$myObj = new myObj(); 
echo $myObj->initWithArray(array(
      'a' => 'myavalue', 
      'b' => 'mybvalue')) 
     ->get('a'); 
0
function initWithArray(array $a){ 
$myObj = new myObj(); 

    foreach($a as $k => $v){ 
    $myObj->$k = $v; 
} 

return $myObj; 
} 

class myObj { 
private $a; 
private $b; 

public function __set($name, $value) { 
    $this->$name = $value; 
} 

public function __get($name){ 
    if($this->$name != null) 
    return $this->$name; 

    return null; 
} 
} 

또는 주석에서 설명한 것처럼 init 함수가 클래스의 멤버 일 경우 더 좋습니다.

+0

'$ a'와'$ b'가 private이기 때문에 이것이 작동하지 않는다고 생각합니다. – NullUserException

+0

아, 그래서, 그것을 알아 차리지 못했습니다. 내가 고칠 수있게 해줘. – usoban

+0

'__get()'에서'$ name'은'null'이 될 수 없다는 점에 유의할 가치가 있습니다. 항상 * 문자열입니다. – adlawson

0

는 다음과 같은 시도 : 다음

class myObj { 
    private $a; 
    private $b; 

    function __construct($passedArray){ 
     $this->a = array_key_exists('a', $passedArray) ? $passedArray['a'] : 'default_value_for_a'; 
     $this->b = array_key_exists('b', $passedArray) ? $passedArray['b'] : 'default_value_for_b'; 
    } 
//Rest of the code 
} 

:

newObj = new myObj(array('a'=> 'myavalue', 'b'=> 'mybvalue')) 
0

당신은 당신이 새로운 객체를 생성 할 때 옵션을 전달하기 위해 클래스 생성자를 사용할 수 있습니다. 이 방법을 사용하면 setOptions 메소드를 분리해야하므로 init 후에도 옵션을 업데이트 할 수 있습니다.

사용과 같이이 클래스 : 또한

$object = new myClass(array('a'=>'foo')); 
$object->setOptions(array('b'=>'bar')); 

클래스객체을 혼동하지 않으려 고 (옵션을 설정하는 두 가지 방법을 보여줍니다). 객체는 인스턴스 인입니다. NullUserException으로

class myClass 
{ 
    private $a; 
    private $b; 

    public function __construct(array $options = null) 
    { 
     if (null !== $options) { 
      $this->setOptions($options); 
     } 
    } 

    public function setOptions(array $options) 
    { 
     foreach ($options as $key => $value) { 
      if (isset($this->$key)) { 
       $this->$key = $value; 
      } 
     } 

     return $this; 
    } 
} 
+0

나는 이것을 다음과 같이 호출 할 수있다 ... $ this-> set_ $ key = $ value; 왜냐하면, 나는 내 자신의 세터를 구현합니다. – DNB5brims

+0

다른 많은 방법을 사용할 수 있습니다. 'set_a()'메소드를 정의한다면, 절대적으로'$ this-> set_a ($ value)'를 호출 할 수있다. – adlawson

0

내가 보통 사람이 속성에 액세스 할 수 있도록 같은 객체를 통해 나에게 총 통제를 제공하는 방식을 채택한다. 허가를 거부하고 응용 프로그램 등에 따라 적절하다고 생각하는 것만 접근 할 수 있도록 허용합니다.

아래 예를 살펴보십시오.

예 위의 예에서 당신은 기본적으로에 조작의 모든 종류를 할 사람을 허용하지된다 비공개로 클래스 속성 $data을 선언, 클래스 속성을보다 효율적으로 제어 할 수있는 방법을 보여줍니다

class MyObj { 

    private $data = array('one' => null, 'two' => null); 

    public function __set($property, $value) { 
     //Only allow to set those properties which is declared in $this->data array 
     if(array_key_exists($property, $this->data)) { 
      return $this->data[$property] = $value; 
     } else { 
      //if you want to throw some error. 
     } 
    } 

    //you can allow or disallow anyone from accessing the class property directly. 
    public function __get($property) { 
     //To deny the access permission, simply throw an error and return false. 
     $error = 'access denied to class property {' . $property . '}'; 
     return false; 
     //Or Else Allow permission to access class property 
     //return $this->data[$property]; 
    } 
} 

클래스 속성을 직접. 수행 할 작업은 PHP의 getter __get() 및 setter __set() 메서드를 통해 수행됩니다. 물론 당신은 당신의 필요에 따라 위의 코드를 수정할 수 있습니다. 단지 몇 줄의 변화가 새롭고 원하는대로 행동 할 것입니다.