• 技术文章 >后端开发 >php教程

    php如何使用链式操作实现四则运算?(代码)

    不言不言2019-01-07 11:33:08转载1553
    本篇文章给大家带来的内容是关于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 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);

    执行结果

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

    以上就是php如何使用链式操作实现四则运算?(代码)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:segmentfault.,如有侵犯,请联系admin@php.cn删除
    专题推荐:laravel php
    上一篇:php中define和const有什么区别?(详解) 下一篇:面向对象是什么
    千万级数据并发解决方案

    相关文章推荐

    • php 和 python 语法(部分)上的区别• PHP 随机数 C扩展随机数• PHP预定义变量9大超全局数组用法详解_php基础• PHP查询附近的人及其距离的实现方法• 浅析php中json_encode()和json_decode()_php基础
    1/1

    PHP中文网