2011-05-05 3 views
4

나는이 MVC OOP 거시기를 배우려고 노력 그리고 난 이상한 오류를 우연히 발견 :PHP 게터/세터

class Foo extends FooBase{ 

    static $_instance; 
    private $_stuff; 

    public function getStuff($which = false){ 
    if($which) return self::app()->_stuff[$which]; else return self::app()->_stuff; 
    } 

    public function setStuff($stuff){ 
    self::app()->_stuff = $stuff; 
    } 

    public static function app(){ 
    if (!(self::$_instance instanceof self)){ 
     self::$_instance = new self(); 
    } 

    return self::$_instance; 
    } 

} 

Foo::app()->stuff = array('name' => 'Foo', 'content' => 'whatever'); 

echo Foo::app()->stuff('name'); // <- this doesn't work... 

FooBase 클래스는 다음과 같습니다 : 코드는 내가 가진

Fatal error: Call to undefined method Foo::stuff() in ... 

:

class FooBase{ 

    public function __get($name){ 
    $getter = "get{$name}"; 
    if(method_exists($this, $getter)) return $this->$getter(); 
    throw new Exception("Property {$name} is not defined."); 
    } 

    public function __set($name, $value){ 
    $setter = "set{$name}"; 
    if(method_exists($this, $setter)) return $this->$setter($value); 
    if(method_exists($this, "get{$name}")) 
     throw new Exception("Property {$name} is read only."); 
    else 
     throw new Exception("Property {$name} is not defined."); 

    } 
} 

그래서 제대로 이해하면 getter 함수에 인수를 사용할 수 없습니까? 왜? 아니면 여기서 뭔가 잘못하고있는 걸까요?

+0

싱글 톤이 개인 생성자를 지정하는 표준 요금이며 PHP의 경우 private'__clone()'메소드도 있습니다. 또한'FooBase'를 추상 클래스로 만들었습니다 – Phil

+0

위의 코드는 주로 Google에서 찾은 자습서의 복사 본문이므로 대부분 이해하지 못합니다. 추상은 무엇을합니까? – Alex

+0

나는 그 자습서에 많은 재고를 넣지 않을 것이다. 당신은 거기에있어 꽤 지저분한이며 일반적으로 구체적인 것들보다 마법 방법을 사용하는 아주 좋은 이유가 필요합니다. 배우고 싶다면 여기에서 시작하십시오 - http://php.net/manual/en/language.oop5.php – Phil

답변

4

타원이있는 것은 모두 메소드로 처리됩니다. 마법 __get__set 방법은 속성처럼 보이는 것에 대해서만 작동합니다.

마법 방법은 __call()을 참조하십시오.

+0

감사합니다. FooBase 내부에 __call 함수를 추가하고 Foo에 callStuff를 추가했습니다. D – Alex