Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback in PHP - I need explanation

Tags:

php

callback

I found code similar to this:

function function_1($callback) 
{
    // not related code removed

    $callback($p);

}

How to call this function? What shall I put in $callback parameter?

Lets say, I want to use function called function_2($p).

like image 544
Kamil Avatar asked Jul 19 '26 01:07

Kamil


1 Answers

Here's the full explanation you want, straight from the php docs: Callbacks.

If you're on php 5.3+, you can pass a lambda (aka anonymous function):

<?php function_1(function ($p) { ... });

If you need support for previous versions of php, you need to define a regular function or instance method. Since the code you've shown is using $callback() instead of call_user_func($callback), you shouldn't need this.

<?php

// without a class
function function_2 ($p) { ... }
function_1('function_2');

// with a class
class A {
    public function function_2 ($p) { ... }

    public function doIt () {
        function_1(array($this, 'function_2'));
    }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!