2013-04-16 3 views
5

에서 메서드 호출 나는 프레임 워크 (OpenCart) 컨트롤러 클래스가 . 나는이 표현이 사용 된 것을 알고 있지만 어떻게 작동하는지 꽤 혼란 스럽다.혼란 클래스와 OpenCart

$this 현재 클래스 즉 ControllerProductProduct 지칭 그것은 $this->response 객체 ControllerProductProduct 또는 상위 클래스 Controller하거나 존재해야 함을 의미한다. 그러나 이것은 사실이 아닙니다. 이 개체는 실제로 부모 클래스 Controller의 보호 된 속성에 Controller::registry->data['response']->setOutput()으로 존재합니다. 그래서 같은 말을 안 :

$this->registry->data['response']->setOutput(); 

대신 $ this-> 응답 ->의 setOutput를();

Controller 클래스의 스 니펫을 제공하므로 아이디어를 얻을 수 있습니다.

abstract class Controller { 
    protected $registry;  
    //Other Properties 
    public function __construct($registry) { 
     $this->registry = $registry; 
    } 
    public function __get($key) { 
     //get() returns registry->data[$key]; 
     return $this->registry->get($key); 
    } 
    public function __set($key, $value) { 
     $this->registry->set($key, $value); 
    } 
    //Other methods 
} 

이 표현식이 어떻게 작동하는지 전혀 모르겠습니까? 이게 어떻게 가능할까요?

감사합니다.

+0

나는 __get 메서드가 선언되어 있지 않고 같은 문제가 생겼다. 또한 사용할 수도있다. http : //stackoverflow.com/questions/23183327/dynamically-adding-new-properties-in- PHP – user3505400

답변

1

마법 방법__get()__set()을 사용하면 매우 쉽게 작동합니다.

액세스 할 수없는 클래스 변수를 가져 오려고 시도하는 경우 (예 : 선언되지 않은 경우) 마법 __get('property_name') 메소드가 호출됩니다.

따라서 당신은 $response를 검색하려고 할 때, 마법의 방법 __get()가 호출되고 (선언에는 $response 속성이 없기 때문에) $this->registry->get('response') 대신 반환됩니다.

예, 대신 $this->registry->get('response')->setOutput($this->render());을 쓸 수는 있지만 이는별로 쓸모가 없으며 많은 글을 쓸 것입니다. PHP가 __get() 메소드를 사용하여 변수를 검색하도록하는 것은 좋지만 너무 깨끗하지는 않습니다.

어쨌든 솔루션에는 아무런 문제가 없습니다.

편집 : 조금 청소기 솔루션이 될 것이다 :

class Controller { 
    //... 
    function getResponse() { 
     return $this->registry->get('response'); 
    } 
    //... 
} 

그런 다음 코드에서 구체적인 방법을 호출 할 수 있고 분명히 충분하다 :

class ControllerProductProduct extends Controller { 
    public function index() 
     //... 
     $this->getResponse()->setOutput($this->render()); 
    } 
} 

그러나 이것은 의미 각각의 가능한 속성에 대해 getXYZ 메서드가 필요하고 __get()은 사용자가 $registry을 추가 작업없이 확장 할 수 있다는 것을 의미합니다 (다른 속성을에 추가 할 경우 설명 함).또 다른 getProperty() 메서드를 추가해야하지만 더 명확하고 깨끗한 솔루션이됩니다.

0

이 마법은 "오버로드"라고합니다. http://php.net/manual/en/language.oop5.overloading.php에서

<?php 

class PropsDemo 
{ 
    private $registry = array(); 

    public function __set($key, $value) { 
     $this->registry[$key] = $value; 
    } 

    public function __get($key) { 
     return $this->registry[$key]; 
    } 
} 

$pd = new PropsDemo; 
$pd->a = 1; 
echo $pd->a; 

봐 :
는 여기 작은 데모입니다. 충분히 명확하게 설명되어 있습니다.