2015-04-23 35 views
-1

假設我有以下類:AttributesQuote給出:PHP - 將對象傳入另一個類的最佳實踐?

class Attributes { 
     private $attr1; 

     public function __construct($attr) 
     { 
       // implementation 
     } 

    } 

    class Quote { 
     private $obj; 

     public function __construct($id, $obj) 
     { 
      $this->obj = $obj; 
      var_dump($this->obj); 
     } 
    } 

我能因此,在某種程度上,通過在對象的構造函數Quote,像這樣:

$attr = new Attributes("1"); 
$quote = new Quote(1, $attr); 

這樣做,只是給了我一個空白頁面?

+0

啓用錯誤報告,看看PHP的錯誤? – Florian

+0

我只是測試你的代碼,並沒有得到任何錯誤這裏出來'對象(屬性)#1(1){[「attr1」:「屬性」:私人] => NULL}' –

+0

@HardikBhavsar - 這是一個完整的例如:http://ideone.com/TBusbx – Phorce

回答

1

它不起作用,因爲您試圖直接訪問變量。你可以讓變量公開,也可以在Attributes類中寫入get函數。

而且你在完整的例子做了一個打字錯誤;)

0

PHP:能見度:http://php.net/manual/en/language.oop5.visibility.php對私人之間的差異細節,protected和public。

這是你的代碼:

<?php 
    session_start(); 

    class Attributes { 

     public $intro; 
     protected $column1; 
     protected $column2; 
     protected $cost; 
     protected $dateValid; 
     protected $TAC; 

     public function __construct($theIntro, $theColumn, $theColumn2, $theCost, $theDateValid, $theTAC) 
     { 
      $this->intro = $theIntro; 
      $this->column1 = $theColumn; 
      $this->column2 = $theColumn2; 
      $this->cost = $theCost; 
      $this->dateValid = $theDateValid; 
      $this->TAC = $theTAC; 
     } 
    } 

    class Quote { 

     private $QuoteID; 
     private $attr; 

     public function __construct($id, $obj) 
     { 
      $this->attr = $obj; 
      $this->QuoteID = $id; 

      echo $this->attr->intro; 

      var_dump($this->attr->intro); 
     } 



    } 


$attr = new Attributes("1", "2", "3", "4", "5", "6"); 
$quote = new Quote("1", $attr); 
?>