dtdb99743 2017-04-07 21:44
浏览 47
已采纳

OOP PHP类从一行调用function1() - > function2()

I am in a new quandary, and have been trying to work with it, I have gotten nothing but errors but I'm some what determined to learn how to do it, and after a bit of searching looks like it cannot be done the say that I want it to be.

In the class there are two or more functions(each can probably be called separably[sp]):

public function functionOne($some_var){
    some other code to be run;
}
public function functionTwo($some_other_var){
    some other code to be run after functionOne(), not called here;
}

From the caller (model):

$tClass = new TestClass();
$result = tClass->functionOne()->functionTwo();
echo $result;

Is this even possible from php? I know it works in frameworks like Laravel, which is where I learned about it. it would be nice... and so I am asking if I am doing it wrong? or ist it even possible, if it is where can i look for more as google had very very little information on the subject.

  • 写回答

1条回答 默认 最新

  • dongzheng3113 2017-04-07 21:47
    关注

    This is called fluent interface and will always work as soon as your method is doing

    return $this;
    

    Most likely it should be a good practice to make all your setters fluent. I would tend to say the only method that cannot be fluent would be your getters, otherwise, all other methods are perfect fit for a fluent interface.

    class calculator {
        private $result = 0;
    
        public multiplication($number) {
            $this->result *= $number;
            return $this;
        }
    
        public addition() {
            $this->result += $number;
            return $this;
        }
    
        /* ... */
    
        public getResult() {
            return $this->result;
        }
    }
    

    Usage:

    $calculator = new calculator();
    echo $calculator->addition(10)->multiplication(2)->getResult(); // 20
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler