dou4624 2016-05-31 07:44
浏览 46
已采纳

在PHP OOP中需要帮助

I'm new in PHP OOP. I need some help for how to write the php OOP class then can call the class like below.

Query->table('user')->column('id','name')->where('name LIKE ?', 
  ["name"=> 'John'])->orderby('name', 'desc');

But, I had try so many time, what I can get it something like below then stop.

Query->table('user')->column('id','name');

I'm running out of ideas and I had google a lot, but fail to find any solution.

Any suitable help is very much appreciated.

  • 写回答

1条回答 默认 最新

  • dongzg2006 2016-05-31 07:49
    关注

    You just need to return on each function of class object itself using $this. All functions that you want to run "in chain" should be public. Check this code:

    <?php
    
    class ClassName
    {
        public function a()
        {
            // ...
    
            return $this;
        }
    
        public function b($param)
        {
            // ...
    
            return $this;
        }
    
        public function c()
        {
            // ...
    
            return $this;
        }
    
    }
    
    // testing
    $obj = new ClassName;
    
    $result = $obj->a()->b('someParam')->c();
    

    You should read about method chaining.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?