How does pointer to function work in PHP?

7

In C you can use function pointers to reference other functions, see an example:

int somar(int a, int b) 
{
    return a + b;
}

int (*sPtr)(int,int);

int main(void) 
{
    sPtr = &somar;

    int r = sPtr(10, 5);

    printf("Soma: %i", r);

    return 0;
}

Output:

  

Sum: 15

In PHP I was able to reference a function just by saving its name in a variable and the same variable started to point to the function. See the example:

<?php
function somar($a, $b) 
{
    return $a + $b;
}

$s = 'somar';

$r = $s(10, 5);

echo 'Soma: ' . $r;

Output:

  

Sum: 15

This way of referencing PHP functions gave me a question that is just below.

Doubt

Is there a pointer to function in PHP, if it exists how does it work?

    
asked by anonymous 17.01.2017 / 17:39

1 answer

6

With PHP, the arithmetic of pointers is a bit obscure for developers, precisely for this reason it is a higher level language.

You can only reference functions in PHP using 3 methods:

  • Anonymous functions, or clojures
  • In this model we can reference a variable as getting the value of a function:

    $fn = function($a, $b) { return $a+$b; };
    
  • Passing as a parameter
  • Just as we pass numbers, we can also execute a function by a

    function exec($fn) {
      return $fn();
    }
    
  • As string
  • By "reflection" PHP can assign the name of a function passed via string to a function pointer (which is exactly what you did above)

    function soma($a, $b) { 
        return $a+$b; 
    }
    
    $e = "soma";
    echo $e(10, 5);
    

    Otherwise I do not think there is any other way. But take a look here:

    17.01.2017 / 18:03