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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?