2011-05-08 5 views
0

아래의 코드와, 좋아, 그래서 :PHP OOP - 잘못된 변수가 반환 되었습니까?

class Core { 
    public $child; 
    public function start() { 
     $child = Loader::instance('Child'); 
     print_r($this); 
    } 
} 

class Loader extends Core { 
    public static $instances; 

    public static function instance($class) { 
     if(!isset(self::$instances[$class])) { 
      self::$instances[$class] = new $class(); 
     } 

     return self::$instances[$class]; 
    } 
} 

class Child extends Core { 
    public function __construct() { 
     parent::__construct(); 

     $this->child = 'test'; 
    } 
} 

Loader::instance('Core')->start(); 

내가 (이 $)를에서 print_r 후 수 있어야합니다 확인합니다 :

Core Object 
(
    [child] => test 
) 

대신

Core Object 
(
    [child] => 
) 

무엇 인 지금 일어나고있는거야?

다시 한 번 감사드립니다 ..

답변

2

Core 클래스의 start() 메서드 내에서 변수 $child을 사용합니다.이 변수는 개체의 속성이 아닙니다. 대신 다음과 같이 작성하십시오.

class Core { 
    public $child; 
    public function start() { 
     $this->child = Loader::instance('Child')->child; 
     print_r($this); 
    } 
} 

이 항목이 성취되었는지 여부를 알려주십시오.

편집 :

나는 당신이 정적 변수를 참조하여 원하는 것을 얻을 수 있다고 생각합니다. 그러나 그들이 어떻게 작동하는지 조심하십시오. 또한 print_r()을 호출하여 결과를 볼 수 없습니다.

class Core { 
    static $child; 
    public function start() { 

     // invoking code that changes Core::$child inside 
     $child = Loader::instance('Child'); 

     print_r($this); 
    } 
} 

class Child extends Core { 
    public function __construct() { 
     parent::__construct(); 

     // changing static variable $child of both Core and Child 
     self::$child = 'test'; 
    } 
} 
+0

그러나 아이가 code'class 아이가 코어를 {확장 변수가 아닌 객체 '아이'.. –

+0

'의 인스턴스가 될 필요가 : 여기

코드입니다 공용 함수 __construct() { parent :: __ construct(); $ this-> variable = 'test'; } } –

+0

@ 가브리엘 답변을 업데이트했습니다 ('-> 자식'추가). 지금 당신에게 효과가 있습니까? – Tadeck

0
$child = Loader::instance('Child'); 

가 될 Shoulld :

$this->child = Loader::instance('Child'); 
0

이 당신의 print_r의 출력이 출처 :

$child = Loader::instance('Child'); 
    print_r($this); 

그리고 현재 개체를 인쇄합니다 ($this 새로 인스턴스화 된 $ 하위가 아닌)클래스).