php链式操作实现四则链式运算

重点在于,返回$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 IMooc\Operation(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)

    原文作者:北方
    原文地址: https://segmentfault.com/a/1190000017775760
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞