如何在PHP类中使用$this仅返回请求的行?

如何在PHP类中使用$this仅返回请求的行?,php,class,scope,Php,Class,Scope,我想链接我的类的方法,比如这样 $article = New Article(); $article->getRow()->addImages(); 因为有时候我不需要在我要求的文章中添加图片 $article->getRow(); 这是我的密码 class Article { protected $connection; public $total; public $item; public function __construct()

我想链接我的类的方法,比如这样

$article = New Article();
$article->getRow()->addImages();
因为有时候我不需要在我要求的文章中添加图片

$article->getRow();
这是我的密码

class Article
{
    protected $connection;
    public $total;
    public $item;

    public function __construct()
    {
        $this->connection = new Database(DSN,DB_USER,DB_PASS);
        $this->connection->connect();
    }

    public function getRow($options = array())
    {
        // Prepare the SQL.
        $sql = "
            SELECT*
            FROM article AS p
            WHERE p.article_id = 'home'
        ";

        $this->total = $this->connection->countRows($sql,array(
            $property->type
        ));


        $this->item = $this->connection->fetchRow($sql,array(
            $property->type
        ));

        return $this;
    }

    public function addImages() {

        $this->item['images']['items'] = array(
            0 => "image 1",
            1 => "image 2"
        );

        $this->item['images']['total'] = 2;

        return $this;
    }

}
$article->getRow()->addImages()的结果

正如您所看到的,
[connection:protected]
始终在结果中,文章的
[total]=>1

但是,如果不执行此操作,我如何将下面这样的结果直接发送到请求的/预期的数据
$article->getRow()->addImages()->item

  Array
    (
        [url] => hello
        [title] => world
        [images] => Array
            (
                [items] => Array
                    (
                        [0] => image 1
                        [1] => image 2
                    )

                [total] => 2
            )

    )
可能吗


我发现
$article->getRow()->addImages()->item
对于获取简单数据来说是“丑陋的”。

当使用
$this
来使用方法链接时,您在返回中固有地传递了整个对象。这就是我们可以使用方法链接的方式,但您似乎完全了解这一点。不过,你想要的似乎有点奇怪:

  • 您希望使用方法链接(意味着您的返回值是
    $this
  • 您只希望接收您的
    项目
    属性(意味着您的返回值不是
    $this
这些似乎是相互排斥的,因为我认真地认为一种方法不能返回两种不同的东西

但是

您可以让
addImages()
函数返回所需的内容。请注意,此解决方案可防止任何进一步的方法链接

public function addImages() {

    $this->item['images']['items'] = array(
        0 => "image 1",
        1 => "image 2"
    );

    $this->item['images']['total'] = 2;

    return $this->item; // HERE you return your item instead
}

您可以向对象添加
url
title
images
属性,并使用unset()删除
connection
total
属性。然后返回这个修改过的对象。
我无法想象你每次都要发送连接信息public function addImages() {

    $this->item['images']['items'] = array(
        0 => "image 1",
        1 => "image 2"
    );

    $this->item['images']['total'] = 2;

    return $this->item; // HERE you return your item instead
}