php鏈式操作實現四則鏈式運算

北方發表於2019-01-05

重點在於,返回$this指標,方便呼叫後者函式。

Operation.php

<?php

namespace IMooc;

class Operation
{
    protected $number = 0;

    public function __construct($number)
    {
        $this->number = $number;
    }
    public function add($number)
    {
        $this->number += $number;
        return $this;
    }

    public function decrease($number)
    {
        $this->number -= $number;
        return $this;
    }

    public function multiply($number)
    {
        $this->number *= $number;
        return $this;
    }

    public function division($number)
    {
        $this->number /= $number;
        return $this;
    }

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

index.php

require __DIR__ . `/IMooc/Operation.php`;
$operation = new IMoocOperation(10);
$result = $operation->add(2)->decrease(2)
    ->multiply(3)->division(4)
    ->get();
var_dump($result);

執行結果

masaki@masaki-Inspiron:/var/www/imooc$ php index.php
float(7.5)

相關文章