[英]Concept of code piping in PHP
假設您想從另一個對象中調用幾個方法。 正確的做法是什么?
如果使用__call()
,是否可以提取參數,而不是將其用作數組。
例:
<?php
class Component
{
protected $borrowMethods = array();
public function __call( $name, $args )
{
if( isset( $this->borrowMethods[$name] ) )
{
$obj = $this->borrowMethods[$name] ;
return $obj->$name( $this->argExtractFunc($args) );
}
throw new \Exception( 'method not exists' );
}
}
class ActiveRecord extends Component
{
protected $validator; //instance of validator
protected $borrowMethods = array(
'validate' => 'validator',
'getError' => 'validator',
'moreMethods' => 'someOtherClass',
);
public function save()
{
if($this->validate())
{
}
}
}
class Validator
{
public function validate(){}
public function getError( $field ){}
}
$ar = new ActiveRecord;
$ar->getError( $field );
不確定我是否完全理解您的要求,但我相信您所指的就是方法鏈接 。 您的每個方法都需要返回$this
(或另一個對象),然后原始調用者可以立即調用該方法。
class Test
{
public function one() {
echo 'one';
return $this;
}
public function two() {
echo 'two';
return $this;
}
}
$test = new Test();
$test->one()->two(); // <-- This is what I think you're trying to do
更新
關於您的更新,我認為這不是好的設計習慣。 $borrowMethods
數組需要多少維護? 您的ActiveRecord
實現與Validator
綁定程度是多少? 相反,為什么不只在ActiveRecord
中實現自己的getError
方法,該方法返回調用$validator->getError($field)
?
您正在尋找的方法稱為方法鏈接 。 看到這個主題: PHP方法鏈接?
__call()
的參數可以通過以下方式獲取: func_get_args()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.