php - 在另一个之前调用方法

标签 php

我有很多方法需要测试远程服务器是否已到达,如果没有,则到达它。

我的第一个想法是 __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/

相关文章:

php - 将数据添加为数组

php - paypal php sdk 在上线时出现 float 问题

声明为 "final"的 PHPUnit Stubbing 类方法

php - PDO: "Invalid parameter number"当用相同的值替换多个参数时

c# - 为什么 PHP 不需要中间层,而其他语言则需要

php - 在 PHP 脚本运行时添加加载图像

php - 表单未重新提交

PHP:字母排列

php - 下载 .zip 文件运行损坏的文件 php

javascript - 在javascript中传递一个值