2013-12-14 107 views
1

我有兩個類獲取包含對象

class Table { 
    public $rows = array(); 
    public $name; 

    public function __construct($name, $rows) { 
     $this->name = $name; 
     $this->rows = $rows; 
    } 
} 

class Row { 
    public $name; 

     public function __construct($name) { 
     $this->name = $name; 
    } 
} 

現在我想創建一個對象表,並添加2行吧。

$rows = array(
    new Row("Row 1"), 
    new Row("Row 2") 
); 
$table = new Table("Table 1", $rows); 

到目前爲止好.. 但有可能得到一個排的含表? 例如:

foreach($table->rows AS $row) { 
    echo $row->name . ' is member of table ' . $row->getContainingTable()->name; 
} 

這僅僅是一個例子...

+0

公共變量是一個壞主意,他們打破封裝。 – GordonM

+0

我知道,但這只是一個示例代碼 – bernhardh

回答

3

你將不得不改變你的類(通過Table對象的話):

class Row { 
    public $name; 
    protected $table; 

    public function __construct($name, Table $table) { 
     $this->name = $name; 
     $this->table = $table; 
    } 

    public function getContainingTable(){ 
     return $this->table; 
    } 
} 

如果你不能在實例化時創建一個setter方法,並在將行傳遞給表後使用它:)

實際上,這裏有一個更好的想法:

class Table { 
    public $rows = array(); 
    public $name; 

    public function __construct($name, array $rows) { 
     $this->name = $name; 
     $this->rows = $rows; 

     foreach($rows as $row) 
      $row->setContainingTable($this); 
    } 
} 

class Row { 
    public $name; 
    protected $table; 

    public function __construct($name) { 
     $this->name = $name; 
    } 

    public function setContainingTable(Table $table){ 
     $this->table = $table; 
    } 

    public function getContainingTable(){ 
     return $this->table; 
    } 
} 
1

我想你應該你的類結構改變這樣的事情

<?php 
class MyCollection implements IteratorAggregate 
{ 
    private $items = array(); 
    private $count = 0; 

    // Required definition of interface IteratorAggregate 
    public function getIterator() { 
     return new MyIterator($this->items); 
    } 

    public function add($value) { 
     $this->items[$this->count++] = $value; 
    } 
} 

$coll = new MyCollection(); 
$coll->add('value 1'); 
$coll->add('value 2'); 
$coll->add('value 3'); 

foreach ($coll as $key => $val) { 
    echo "key/value: [$key -> $val]\n\n"; 
} 
?> 

看看iterators in php 5,看到了例子這個例子是從那裏