![](/img/trans.png)
[英]Chaining methods in PHP and execute the first called method as last, how does it work?
[英]When chaining methods in PHP, Is it possible to determine which method was called first?
因此,我現在正在編寫一個PHP類,以幫助簡化SQL語句的構造。 我正在編寫它們,以便每個方法都返回對象的實例( return $this
)以便啟用方法鏈接。
是否可以測試被調用的方法是否是方法鏈的一部分,以及方法鏈中已經執行了哪些方法? 例如,在下面的代碼中,我希望使用“ from”方法來測試它是否直接在其前面的select()
方法中作為鏈的一部分被調用。
$object->select('john', 'chris')->from('people');
提前致謝!
我認為沒有必要檢查調用方法的順序。 您可以創建一個finally方法(例如execute()
),並在其中檢查查詢所需的所有屬性,如果缺少任何屬性(例如select
),則可以為其設置默認值:如果可用(例如'select' => '*'
)。
但是無論如何,如果要檢查的是在具體方法之前調用的某種方法,則可以設置private
屬性來滿足方法要求。 例如:
private $_methodsRequirements = array(
'from' => array('select'),
'set' => array('update', 'where'),
// and all requiriments for each method
)
private $_calledMethods = array();
並創建用於檢查方法“可調用性”的其他方法:
private function checkCallability($method) {
$requiredMethods = $this->_methodsRequirements[$method];
foreach($requiredMethods as $m) {
if(!in_array($m, $this->_calledMethods)) {
throw new Exception('You must call method "'.$m.'" before calling method "'.$method.'"!');
}
}
return true;
}
在每種方法開始時,您必須調用它:
public function select() {
$this->checkCallability(__METHOD__);
// your query generation
array_push($this->_calledMethods, __METHOD__);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.