dtwknzk3764 2014-12-11 04:07
浏览 27
已采纳

理解PHP中的依赖注入

class Author {
    private $firstName;
    private $lastName;

    public function __construct($firstName, $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }

    public function getFirstName() {
        return $this->firstName;
    }

    public function getLastName() {
        return $this->lastName;
    }
}

class Question {
    private $author;
    private $question;

    public function __construct($question, Author $author) {
        $this->author = $author;
        $this->question = $question;
    }

    public function getAuthor() {
        return $this->author;
    }

    public function getQuestion() {
        return $this->question;
    }
}

Class author is injected into the constructor of Question class am I correct? but how to call the Question class to get the author's name?

$question = new Question('What is PHP', 'Adam');
$question->getFirstname;

like this? I assume Question class inherited Author class so Question's instance can use the function of Author Class?

  • 写回答

2条回答 默认 最新

  • dqrnsg6439 2014-12-11 04:15
    关注

    Simple

    echo $question->getAuthor()->getFirstName();
    

    Think of it this way if it helps

    $author = $question->getAuthor();
    echo $author->getFirstName();
    

    Also note that you can't construct a Question with the string "Adam", you need to pass an instance of Author

    $question = new Question('What is PHP', new Author('Adam', 'Lastname'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码