drsdvwsvo78320812 2014-01-18 20:03
浏览 120
已采纳

PHP依赖注入 - 调用注入对象的方法

I'm learning about dependency injection in php and I think there's something I'm missing.

I created two classes, Author and Article:

class Author{
    private $firstName;
    private $lastName;

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

    public function getName(){
        return $this->firstName . " " . $this->lastName;
    }
}

class Article{
    private $author;
    private $content;

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

    public function getContent(){
        return $this->content;
    }
}

Then, on my index page, I instantiated my Article class and injected my Author class:

require "Classes.php";
$Article = new Article( new Author("Chris", "Schmitz"), "this is the content of my article");

print_r($Article);

Which prints out my object as expected:

Article Object ( [author:Article:private] => Author Object ( [firstName:Author:private] => Chris [lastName:Author:private] => Schmitz ) [content:Article:private] => this is the content of my article ) 

This all makes sense, but when I go to call the public method getName() from my Author class I get an error:

echo $Article->author->getName();
// produces php error: PHP Fatal error:  Cannot access private property Article::$author

If I'm injecting one object into the other, shouldn't I be able to access the injected object's public methods? Am I misunderstanding how the injection is expected to work? Did I set it up wrong?

  • 写回答

1条回答 默认 最新

  • dongxun2903 2014-01-18 20:05
    关注

    $author is a private property of Article, meaning you can only access it from methods inside that class.

    Although the getName() method is indeed public, all parts of the -> chain have to be visible from the context in which you're using them - unfortunately author isn't.

    As suggested by Halim, the cleanest way to address the error is to create a public getter method for the author property in your Article class:

    public function getAuthor() {
        return $this->author;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn