dtdb99743
dtdb99743
2017-04-07 21:44

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 dongzheng3113 4年前

    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
    
    点赞 1 评论 复制链接分享

相关推荐