0

I couldn't google this one. The question;

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

Consider $endpoint is a variable and $args is an array of a class. We want to pass the variable $this->{$this->endpoint}($this->args) to _response() method. What does {$this->endpoint}($this->args) means in php syntax?

The link of full definition of code: http://coreymaynard.com/blog/creating-a-restful-api-with-php/

  • If this isn't already a duplicate, it should be added to http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – zzzzBov Apr 12 '16 at 17:08
  • This is due to using [variable variables](https://secure.php.net/manual/language.variables.variable.php) - or in this case variable method names. But as far as I know considered bad practice, you can use [`call_user_func()`](https://secure.php.net/call_user_func) instead – kero Apr 12 '16 at 17:10
  • @zzzzBov This is not covered in the linked question, or am I just unable to find it there? – kero Apr 12 '16 at 17:11
  • @kingkero, I didn't see it covered in the question I linked, but there may be alternative questions that this is a duplicate of – zzzzBov Apr 12 '16 at 17:20
  • 1
    Possible duplicate of [PHP curly brace syntax for member variable](http://stackoverflow.com/questions/1147937/php-curly-brace-syntax-for-member-variable) – Sebastian Brosch Apr 12 '16 at 17:21

1 Answers1

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

Divide and conquer:

$this->_response()

Means calling the method _response() of the current object with the argument

$this->{$this->endpoint}($this->args)

The curly braces are explained here: http://php.net/manual/en/language.types.string.php

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.

Therefore {$this->endpoint} evaluates to a string which was previously set as endpoint property of the current object.

$this->endpointproperty($this->args)

There must be a method endpoint property in the current object which accepts one argument. This Argument is also a property of this object:

$this->args
Blackbam
  • 17,496
  • 26
  • 97
  • 150
  • 1
    It means I can call the method that its name is inside my $endpoint variable. If api call is like ".../cars/mercedes/2015", it means I have a cars() method and I'm passing it the ['mercedes,'2015'] array. omg. Thanks. – Mehmet Cetin Apr 12 '16 at 17:41