2011-10-19 167 views
0

我想從另一個類的另一個類創建對象。 所以我做到了:在類的構造函數中創建另一個對象

class National_Number{ 
    private $num = array(); 
    public function __construct($first = NULL,$second = NULL,$third = NULL) { 
     $this->set($first,0); 
     $this->set($second,1); 
     $this->set($third,2); 
    } 
    public function set($num = NULL,$part = 0) 
    { 
     if ($num != NULL AND $part num[$part] = $num; 
      else 
       return FALSE; 
     } 
     else 
     { 
     return FALSE; 
     } 
    } 
    public function get($part = 0) 
    { 
     if ($part num[$part]; 
     else 
      return FALSE; 
    } 
} 
class Temp { 
    private $ID; 
    public function __construct() { 
     $ID = new National_Number(127,110,8100); 
    } 
    public function _get() 
    { 
     var_dump($ID->get()); 
    } 
} 
$temp = new Temp(); 
$temp->_get(); 

國家代碼將正常工作,但臨時類是行不通的,問題出在哪裏?

+5

嘗試了'$ this-> ID'呢?而這裏看起來像破損的代碼:'if($ part num [$ part];'..你有什麼問題ctrl + c? – Lukman

回答

1

唐`噸忘記使用 「$這個 - >」 訪問類成員時,更新的代碼=>

class National_Number{ 
      private $num = array(); 
      public function __construct($first = NULL,$second = NULL,$third = NULL) { 
       $this->set($first,0); 
       $this->set($second,1); 
       $this->set($third,2); 
      } 
      public function set($nume = NULL,$part = 0) 
      { 
       if ($nume != NULL AND $part){ 
        $this->num[$part] = $nume; 
       } 
        else 
         return FALSE; 
       } 


      public function get($part = 0) 
      { 
       if (isset($this->num[$part])){ 
        return $this->num[$part]; 
       } 
       else 
        return FALSE; 
      } 
     } 
     class Temp { 
      private $ID; 
      public function __construct() { 
       $this->ID = new National_Number(127,110,8100); 
      } 
      public function _get() 
      { 
       var_dump($this->ID->get(1)); 
      } 
     } 
     $temp = new Temp(); 
     $temp->_get(); 
     ?> 
1

$ID是一個局部變量,僅在__construct()有效。如果要引用的屬性,你必須使用$this->ID

$this->ID = new National_Number(127,110,8100); 

同爲__get()

相關問題