2013-12-14 108 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,看到了例子这个例子是从那里