Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP / Scope / Callback

class myClass { $myVariable = 'myCallback';

    function myFunction() {
        $body = false;
        $callback = $this->myVariable;

        function test($handle, $line) {
            global $body, $callback;

            if ($body) {
                call_user_func($callback, $line);
            }

            if ($line === "\r\n") {
                $body = true;
            }

            return strlen($line);
        }

        ...
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'test');
        ...
    }
}

function myCallback($data) {
    print $data;
}

$myCls = new myClass();
$myCls->myFunction();

Warning: call_user_func() [function.call-user-func]: First argument is expected to be a valid callback !

My $callback value is empty, how can I resolve this issue ? Restriction : myCallback function cannot be changed !

like image 433
bernedef Avatar asked Dec 09 '22 14:12

bernedef


1 Answers

Important: This is only possible in PHP >= 5.3. The OP does not use PHP 5.3 but I will leave the answer here in case someone has a similar problem and uses PHP 5.3.


$callback is not a global variable, it is local in the methods scope. From the documentation:

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

Make use of use (and assign the function to a variable):

$test = function($handle, $line) use ($callback, $body){

    if ($body) {
        call_user_func($callback, $line);
    }

    if ($line === "\r\n") {
        $body = true;
    }

    return strlen($line);
};

and later:

curl_setopt($ch, CURLOPT_WRITEFUNCTION, $test);
like image 100
Felix Kling Avatar answered Dec 23 '22 21:12

Felix Kling