내가 보통 사람이 속성에 액세스 할 수 있도록 같은 객체를 통해 나에게 총 통제를 제공하는 방식을 채택한다. 허가를 거부하고 응용 프로그램 등에 따라 적절하다고 생각하는 것만 접근 할 수 있도록 허용합니다.
아래 예를 살펴보십시오.
예 위의 예에서 당신은 기본적으로에 조작의 모든 종류를 할 사람을 허용하지된다 비공개로 클래스 속성 $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()
메서드를 통해 수행됩니다. 물론 당신은 당신의 필요에 따라 위의 코드를 수정할 수 있습니다. 단지 몇 줄의 변화가 새롭고 원하는대로 행동 할 것입니다.
'myObj'의 private 변수에 액세스해야하기 때문에이 init 메소드는 실제로 클래스의 멤버 여야합니다. – NullUserException
배열과 같이 객체를 사용하려면 PHP 기본 제공 Iterator 인터페이스를 사용하는 것이 좋습니다. http://www.php.net/manual/en/class.iterator.php –