How does function pointer work in PHP?

Asked

Viewed 255 times

7

In C it is possible to use pointers in functions 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;
}

Exit:

Sum: 15

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

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

$s = 'somar';

$r = $s(10, 5);

echo 'Soma: ' . $r;

Exit:

Sum: 15

This way of referencing PHP functions generated me a doubt that is just below.

Doubt

There is a pointer to a function in PHP, if it exists how it works?

1 answer

6


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

It is only possible to reference PHP functions using 3 methods:

  1. Functions Anonimas, or clojures

In this model we can reference a variable as obtaining the value of a function:

$fn = function($a, $b) { return $a+$b; };
  1. Passing as parameter

Just as we pass numbers, we can also execute a function by a parameter

function exec($fn) {
  return $fn();
}
  1. 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);

Other than that I believe there is no other way. But take a look here:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.