我正在尝试为项目构建一些类,我想知道如何实现以下目标。我不确定如何用语言问这个,但我会提供一个例子:
class Table{
private $name;
private $fields = [];
public function addField(Field $field){
$this->fields[$field->getName()] = $field;
}
public function getName(){
return $this->name;
}
}
class Field{
private $name;
public function getName(){
return $this->name;
}
public function getTableName(){
//return Table::getName
}
public function getTable(){
//return a ref to the Table object
}
}
$table = new Table();
$field = new Field();
$table->addField($field);
我想在这里实现,一旦将$字段添加到$ table,就有某种方法从$ field对象中的任何方法获取$ table的引用
我非常感谢任何帮助或想法如何重组它,以便我可以实现我的目标
提前谢谢
答案 0 :(得分:1)
class Table{
private $name;
private $fields = [];
public function addField(Field $field){
$this->field->setTable($this);
$this->fields[$field->getName()] = $field;
}
public function getName(){
return $this->name;
}
}
class Field{
private $name;
private $relatedTable;
public function getName(){
return $this->name;
}
public function setName($name){
$this->name = $name;
}
public function getTableName(){
return $this->relatedTable->getName();
}
public function getTable(){
return $this->relatedTable;
}
public function setTable(Table $table){
$this->relatedTable = $table;
}
}
$field = new Field;
$field->setName('Field1');
$table = new Table;
$table->addField($field);
echo $field->getTable()->getName();
虽然你必须要知道当你将一个对象传递给一个函数时,它会被“引用”传递(我知道还有另一个术语。)
// in case you're running it in a for loop
$field = new Field;
$table = new Table;
for($i = 0; $i < 3; $i++)
{
$field->setName("Field{$i}");
$table->addField(clone $field); // notice the clone there.
}
我认为这种方法与 Observer Pattern
类似