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)

不言
Release: 2023-04-04 17:04:01
forward
3091 people have browsed it

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;
    }
}
Copy after login

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);
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template