我有很多方法需要测试远程服务器是否已到达,如果没有,则到达它。
我的第一个想法是 __call 魔术方法,但该方法仅在真正的方法(具有原始名称)未呈现时被调用。
<?php
public function __call( $name, $arguments ) {
$needsExecution = array(
'getBody', 'getHeader', 'getHeaders', 'getRawOutput',
'getStatusCode', 'getFullHttp'
);
if ( in_array( $name, $needsExecution ) ) {
if ( !$this->hasBeenExecuted() ) {
$this->execute();
}
}
}
public function getBody() {
return $this->responseBody;
}
public function getHeaders() {
return $this->responseHeaders;
}
?>
我真的需要在每个方法中都有一堆 if 还是有更好的方法?
最佳答案
像这样更改您的代码怎么样:
<?php
public function __call( $name, $arguments ) {
$needsExecution = array(
'getBody', 'getHeader', 'getHeaders', 'getRawOutput',
'getStatusCode', 'getFullHttp'
);
if ( in_array( $name, $needsExecution ) ) {
if ( !$this->hasBeenExecuted() ) {
$this->execute();
}
return $this->{'_' . $name}();
//return call_user_func(array($this, '_' . $name));
}
}
protected function _getBody() {
return $this->responseBody;
}
protected function _getHeaders() {
return $this->responseHeaders;
}
?>
关于php - 在另一个之前调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8303140/