2011-09-07 5 views
0
<?php 

class FirstClass{ 
    public static $second; 
    public static $result = 'not this =/'; 
    public function __construct(){ 
     $this->result = 'ok'; 
     $this->second = new SecondClass(); 
    } 

    public function show(){ 
     echo $this->second->value; 
    } 
} 

class SecondClass extends FirstClass{ 
    public $value; 
    public function __construct(){ 
     $this->value = parent::$result; //Make it get "ok" here 
    } 
} 

$temp = new FirstClass(); 
$temp->show(); //It will show: "not this =/" 

?> 

어떻게하면 "ok"를 인쇄 할 수 있습니까?PHP 클래스 - 클래스에 부모를 알려주는 값을 어떻게 만들 수 있습니까?

즉, SecondClass는 어떤 FirstClass가 결과로 설정했는지 알아야합니다.

답변

2

$this->result = 'ok';self::$result = 'ok';으로 바꾸고 FirstClass 생성자로 바꾸십시오.

Btw, 코드가 끔찍합니다. 정적 변수와 인스턴스 변수를 섞어서 클래스를 확장하고 있지만 확장 기능의 이점은 사용하지 마십시오.

1

첫 번째 클래스에서 self :: $ result as static을 참조해야합니다. 다음은

은 ... 당신이 원하는 일을해야

<?php 

class FirstClass{ 
    public static $second; 
    public static $result = 'not this =/'; 
    public function __construct(){ 
     self::$result = 'ok'; 
     $this->second = new SecondClass(); 
    } 

    public function show(){ 
     echo $this->second->value; 
    } 
} 

class SecondClass extends FirstClass{ 
    public $value; 
    public function __construct(){ 
     $this->value = parent::$result; //Make it get "ok" here 
    } 
} 

$temp = new FirstClass(); 
$temp->show(); //It will show: "not this =/" 

?> 
관련 문제