创建两个对象之间的链接


Create a link between two objects

这个问题可能有点不清楚,但是,我将尽力解释我的意思。在现代编程中,任何东西都必须是对象!举个例子:假设我有一个名为"Language"的对象,当然,每种语言都由许多短语组成,所以我有另一个名为"Phrase"的对象,现在,我如何在这个"Language"对象和"Phrase"之间创建一个链接,就像我说的" x短语是y语言的一部分,y语言包含那个x短语",我如何通过编程来实现,例如在php中如何实现?

我希望你明白我的意思。

说到使用对象,最好的方法是从创建类开始。在您的示例中,应该同时创建LanguagePhrase类。参见下面的示例代码:

Language.class.php

<?php
class Language {
  private $phrases = array();
  public function phrases() {
   return $this->phrases;
  }
  public function addPhrase(Phrase $phrase) {
   array_push($this->phrases, $phrase);
  }
  public function getPhraseByIndex($index) {
   if(!is_null($this->phrases[$index]))
    return $this->phrases[$index];
   else
    return null;
  }
  public function removePhraseByIndex($index) {
   unset($this->phrases[$index]);
   array_values($this->phrases);
  }
}
?>

Phrase.class.php

<?php
class Phrase {
  private $text;
  public function __construct($text) {
    $this->update($text);
  }
  public function update($text) {
   $this->text = $text;
  }
  public function getText() {
   return $this->text;
  }
}
?>

希望这能回答你的问题

哎呀,有点晚了。@Robin提供了一个很好的答案。无论如何,我也包括了如何使用它。

class Language {
    private $phrases = array();
    public function addPhrase(Phrase $phrase) {
        $this->phrases[] = $phrase;
    }
    public function getPhrases() {
        return $this->phrases;
    }
}
class Phrase {
    private $value = null;
    function __construct($value) {
        $this->value = $value;
    }
    public function Value() {
        return $this->value;
    }
}
$language = new Language();
$language->addPhrase(new Phrase("phrase1"));
$language->addPhrase(new Phrase("phrase2"));
foreach($language->getPhrases() as $phrase)
    printf("%s'n", $phrase->Value());

你所要求的被称为依赖注入,这意味着如果另一个对象依赖它,你必须注入它。

有三种注入方式:构造函数注入、方法注入和属性注入。

@msfoster已经向您展示了如何通过方法进行注入,这正是您所需要的。

其他两种方式参见php中的依赖注入

PHP对象。这是我能做的最好的解释了。

$english = (object) array('phrases' => array ('1' => 'Phrase one here', '2' => 'Phrase two here', '3' => 'Phrase three here'));

或者两者都是对象

$english_phrases = array('Phrase one here', 'Phrase two here', 'Phrase three here');
$english = array('phrases' => $phrases);