Method Chains PHP OOP

后端 未结 3 1042
自闭症患者
自闭症患者 2020-12-03 17:52

Commonly, in a lot of frameworks, you can find examples of creating a query using the query builder. Often you will see:

$query->select(\'field\');
$query         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-03 18:20

    Basically, you have to make every method in the class return the instance:

    x = $x;
        }
        public function __toString(){
            return 'condition is ' . $this->x;
        }
    }
    class Foo{
        public function select($what){
            echo "I'm selecting $what\n";
            return $this;
        }
        public function from($where){
            echo "From $where\n";
            return $this;
        }
        public function where($condition){
            echo "Where $condition\n";
            return $this;
        }
        public function limit($condition){
            echo "Limited by $condition\n";
            return $this;
        }
        public function order($order){
            echo "Order by $order\n";
            return $this;
        }
    }
    
    $object = new Foo;
    
    $object->select('something')
           ->from('table')
           ->where( new Object_Evaluate('x') )
           ->limit(1)
           ->order('x');
    
    ?>
    

    This is often used as pure eye candy but I suppose it has its valid usages as well.

提交回复
热议问题