說明
重點在於每個串接的 function 都必須把物件的實體傳回來(return $this),這樣就能不斷的重覆呼叫,就像 jQuery 的寫法一樣
不囉嗦,直接看 code 吧!

<?php
class Number
{
    private $value = 0;

    // 初始化
    function __construct($n)
    {
        $this->value = $n;
    }
    
    // 加
    public function add($n)
    {
        $this->value += $n;
        return $this;
    }

    // 減
    public function subtract($n)
    {
        $this->value -= $n;
        return $this;
    }

    // 乘
    public function times($n)
    {
        $this->value *= $n;
        return $this;
    }

    // 除
    public function divided($n)
    {
        $this->value /= $n;
        return $this;
    }

    public function get()
    {
        return $this->value;
    }
}

// Class 串接寫法測試
// 目前測試在 PHP 5.2.17 及 5.4.16 皆能正常執行
$a = New Number(3);
echo "3 - 1 + 2 = " . $a->subtract(1)->add(2)->get();

// 輸出的結果為 3 - 1 + 2 = 2
arrow
arrow
    文章標籤
    php class
    全站熱搜

    wbkuo 發表在 痞客邦 留言(0) 人氣()