我想鏈我類的方法,如用這種方法,
$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()
,
Article Object
(
[connection:protected] => Database Object
(
[connection:protected] => PDO Object
(
)
[dsn:protected] => mysql:host=localhost;dbname=xxx
[username:protected] => xxx
[password:protected] => xxx
)
[item] => Array
(
[url] => hello
[title] => world
[images] => Array
(
[items] => Array
(
[0] => image 1
[1] => image 2
)
[total] => 2
)
)
[total] => 1
}
正如您所看到的那樣,[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
對於獲取簡單的數據是'醜陋'。
您可以添加'url','title'和'images'屬性的對象,並通過取消設置刪除'connection'和'total'屬性() 。然後返回這個修改的對象。 – Phantom
'我無法想象你每次都必須發送連接信息。 「那麼你會怎麼做呢? – laukok