問題描述
通常,在許多框架中,您可以找到使用查詢構建器創建查詢的示例.你經常會看到:
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->from('entity');
但是,在某些框架中你也可以這樣做
However, in some frameworks you can also do it like this
$object->select('field')
->from('table')
->where( new Object_Evaluate('x') )
->limit(1)
->order('x', 'ASC');
您實際上是如何制作這種鏈條的?
How do you actually do this kinds of chains?
推薦答案
這叫做 Fluent Interface -- 該頁面上有一個 PHP 示例.
This is called Fluent Interface -- there is an example in PHP on that page.
基本思想是該類的每個方法(您希望能夠鏈接) 必須返回 $this
-- 這使得調用其他方法成為可能返回的 $this
上同一個類的方法.
The basic idea is that each method (that you want to be able to chain) of the class has to return $this
-- which makes possible to call other methods of that same class on the returned $this
.
當然,每個方法都可以訪問類的當前實例的屬性——這意味著每個方法都可以向當前實例添加一些信息".
And, of course, each method has access to the properties of the current instance of the class -- which means each method can "add some information" to the current instance.
這篇關于方法鏈 PHP OOP的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!