Domain Empire

PHP: How to pass a function as parameter?

Spaceship Spaceship
Watch
Impact
0
PHP: How to pass a function as an argument?

In PHP, what is the way to pass a function as an argument in an other function?
 
Last edited:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Well if you want to call a function you can use the call_user_func function. If you need to pass the function name as parameter you would do this...

Code:
<?php
function myFunction($callbackFunc)
{
    // Do whatever you got to here...

   // and then..
    call_user_func($callbackFunc);
}
?>

Hope this helps. :)
 
0
•••
Thanks a lot. But my problem is more complicated:

<?php

class a
{
public function f()
{
echo "af";
}
}

function func($g)
{
class b extends a
{
public function f()
{
echo "bf";
// I want to call function g from here
}
}
$b1 = new b();
$b1->f();
}

function g()
{
echo "g";
}

// From here I want to call function func with argument the funtion g

?>
 
0
•••
why have you got a class within a function (class b is within the func function)?

This looks like very bad code design.
 
0
•••
I need to call the following lines of code -the body of function func- from many locations in my application. So I use a function. Is it a bad idea?
(class a -not b- has a lot lines of code)
Also functions like g are more than 50!

class b extends a
{
public function f()
{
echo "bf";
// I want to call function g from here
}
}
$b1 = new b();
$b1->f();
 
Last edited:
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back