2014-07-11 31 views
1

我想鏈我類的方法,如用這種方法,

$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對於獲取簡單的數據是'醜陋'。

+1

您可以添加'url','title'和'images'屬性的對象,並通過取消設置刪除'connection'和'total'屬性() 。然後返回這個修改的對象。 – Phantom

+0

'我無法想象你每次都必須發送連接信息。 「那麼你會怎麼做呢? – laukok

回答

1

當使用$this來使用方法鏈接時,您固有地在返回時傳遞整個對象。這是我們如何使用方法鏈,但你似乎完全意識到這一點。你的願望似乎有點奇怪,但:

  • 你想使用方法鏈接(這意味着你的返回值是$this
  • 你想只收到您的item財產(這意味着您的返回值不是$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 
} 
+1

明白了。感謝你的回答。我想要的確很奇怪! – laukok

相關問題