Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 先调用另一个方法_Php - Fatal编程技术网

Php 先调用另一个方法

Php 先调用另一个方法,php,Php,我有很多方法,我需要测试远程服务器是否被访问,如果没有,就访问它 我的第一个想法是uuu调用magic method,但是只有当real method(使用原始名称)未出现时,才称该方法为 <?php public function __call( $name, $arguments ) { $needsExecution = array( 'getBody', 'getHeader', 'getHeaders', 'getRawOutput', '

我有很多方法,我需要测试远程服务器是否被访问,如果没有,就访问它

我的第一个想法是uuu调用magic method,但是只有当real method(使用原始名称)未出现时,才称该方法为

<?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;
}

?>

在我看来,你把这件事复杂化了。(假设我理解你的问题。)

为什么不让与远程服务器对话的功能在完成时设置一个标志呢


为什么需要检查连接的每个阶段?为什么它们是分开的阶段呢?它们不是都按照特定的顺序一起工作,而且从不来自任何其他代码吗?没有任何理由使它们具有单独的功能。(除非你的代码有更多我不知道的地方。)

我不确定你在做什么……但是如果你想拦截每个方法调用

class ObjectProxy {
    protected $obj;
    function __construct($obj) {
        $this->obj = $obj;
    }
    function __call($methodName, $arguments) {
        //do stuff
        return call_user_func_array($methodName, $this->obj, $arguments);
    }
}

$proxied = new ObjectProxy(new OrigionalType());
$proxied->getBody();

您可能希望实现更多的神奇方法,以使其适用于多个实例方法调用,但您明白这一点。这不是一个适用于所有情况的解决方案,但有时很方便。

是的,它是合法的:
$this->{''.'$funtionName}()