获取包含对象

时间:2013-12-14 15:03:23

标签: php

我有两个班级

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;
}

这只是一个例子......

2 个答案:

答案 0 :(得分:3)

您必须更改Row类(将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 :(得分: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并查看此示例的示例是从那里到