Sarath Kumar
Sarath Kumar

Reputation: 1146

A function returns another function in php

I dont know whether the question (the way I asked) is correct or not. I'm open for your suggestion. I want to know how exactly the following code works. If you want any details I can provide as much I want.

public function processAPI() {
    if (method_exists($this, $this->endpoint)) {
        return $this->_response($this->{$this->endpoint}($this->args));
    }
    return $this->_response("No Endpoint: $this->endpoint", 404);
}

private function _response($data, $status = 200) {
    header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
    return json_encode($data);
}
private function _requestStatus($code) {
    $status = array(  
        200 => 'OK',
        404 => 'Not Found',   
        405 => 'Method Not Allowed',
        500 => 'Internal Server Error',
    ); 
    return ($status[$code])?$status[$code]:$status[500]; 
}
/**
 * Example of an Endpoint
 */
 protected function myMethod() {
    if ($this->method == 'GET') {
        return "Your name is " . $this->User->name;
    } else {
        return "Only accepts GET requests";
    }
 }

Here $this->endpoint is 'myMethod' (a method I want to execute)

I pass the method which I want to execute in the url. The function catches the request process then call the exact method. I want to how it's works. Especially this line.

return $this->_response($this->{$this->endpoint}($this->args));

Upvotes: 0

Views: 203

Answers (1)

R. Chappell
R. Chappell

Reputation: 1292

PHP Supports both variable functions and variable variables.

When it reaches you statement within processApi

return $this->_response($this->{$this->endpoint}($this->args));

PHP will resolve your endpoint variable, we'll replace it with myMethod which is in your example:

return $this->_response($this->myMethod($this->args));

As you can see, we're now calling a method which exists on your class. If you set the endpoint to something which didn't exist, it would throw an error.

If myMethod returns a string such as my name is bob then once $this->myMethod($this->args) executes PHP will resolve that value as the argument for $this->_response() resulting in:

return $this->_response('my name is bob');

Following that chain of events, the processAPI() method will finally return that string JSON encoded as that's what the _response method does.

Upvotes: 2

Related Questions