dongxiang3648 2014-10-07 03:38
浏览 21
已采纳

PHP续函数[重复]

This question already has an answer here:

Hi how can I make a class object with the possibility of doing this:

<?php
    $someClass = new SomeClass;
    $sum = $someClass->addValues(1,22)->sumValues();
    echo $sum; // to give me 23
?>

Sorry for asking! This is what I meant and I just got the idea, so - Sorry for the Post.

<?php 
    class SomeClass {
        private $values = array();
        public function addValue(){
            $this->values = func_get_args();
            return $this;
        }

        public function getSum(){
            $sum = array_sum($this->values);
            return $sum;
        }

    }

    $SomeClass = new SomeClass;
    $result = $SomeClass->addValue(1,22,44,51)->getSum();
    echo $result;
?>

And for all of those who answered - Sorry but this was only an EXAMPLE, so I asked How to do it to help me not to argue with me is it an overkill or not. I needed the way to do it. Not like I will use the same code.

</div>
  • 写回答

2条回答 默认 最新

  • dongpian2559 2014-10-07 03:47
    关注

    If you just want to sum a list of numbers then it can easily be done like this:

    $sum = array_sum(array(1, 22));
    

    If you are trying to learn how to use classes/objects then you can implement that like this:

    class SomeClass {
        protected $values = array();
        public function addValues() {
            $this->values = array_merge($this->values, func_get_args());
            return $this;
        }
        public function sum() {
            return array_sum($this->values);
        }
    }
    $someClass = new SomeClass;
    echo $someClass->addValues(1, 22)->sum(); // 23
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果