在两个对象之间创建链接

时间:2014-08-04 20:56:10

标签: php class oop

这个问题可能有点不清楚,但是,我会试着解释一下我的意思。在现代编程中,每件事都必须是一个对象!例如:假设我有一个名为“语言”的对象,当然每个语言都包含许多短语,所以我有另一个名为“Phrase”的对象,现在,我如何在这个“语言”对象之间创建一个链接,和“短语”一样,就像我说“x短语是y语言的一部分,而y语言包含x短语。”,我怎么能以编程方式说,我怎么能在php中说这个例子呢?

我希望你理解我的意思。

4 个答案:

答案 0 :(得分:1)

谈到使用对象,最好的方法是创建类。在您的情况下,您应该同时创建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;
  }

}
?>

希望这能回答你的问题。

答案 1 :(得分:0)

加,有点迟到。 @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());

答案 2 :(得分:0)

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

有3种注射方式:构造函数,方法和属性注入。

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

对于其他两种方式,请参阅dependency injection in php

答案 3 :(得分:-1)

带对象的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);