使用 $this 时调用未定义的方法

Call to undefined method when using $this

我在使用 $this 时遇到了一些问题。

我有一个控制器:

class UserController {
    public function show() {
        // prepare $array from database
        if ok
            return Response::toJson($array);
        else
            return Response::respondWithError("errorMessage");
    }
}

响应 class:

class Response
{
    private function respond($array)
    {
        //do som
    }

    public function toJson($array)
    {
        // do som
        $this->respond($array);
    }

    public function respondWithError($message)
    {
        // do som
        $this->respond($array);
    }
}

我收到错误:

Call to undefined method UserController::respond()

为什么 $this 不是 Response class 而是 UserController?我如何从 foo() 调用 respond() 方法?

您不能在 STATIC 方法中使用方法,因为那样会破坏 encapsulation of OO

首先,你把$foo当成static,所以声明成static,这样就更清楚了...
您不能在静态方法上使用 $this...
你可以使 respond() 静态然后使用 self::respond()

你不能在foo中使用$this,你也必须定义respond static:

class UserController {
    public function show() {
        // do something
        return Response::foo($array);
    }
}
class Response {
    private static function respond() {
        // do something
    }

    public static function foo($array) {
        // do
        return self::respond();
    }
}