Home >Backend Development >PHP Tutorial >How to use chain operations to implement four arithmetic operations in PHP? (code)

How to use chain operations to implement four arithmetic operations in PHP? (code)

不言
不言forward
2019-01-07 11:33:083115browse

The content of this article is about how PHP uses chain operations to implement four arithmetic operations? (code), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The key point is to return the $this pointer to facilitate calling the latter function.

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 pision($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)->pision(4)
    ->get();
var_dump($result);

Execution result

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

The above is the detailed content of How to use chain operations to implement four arithmetic operations in PHP? (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete