Wait for php callback on object instance and return value on function

I have the following function that instantiates an object and runs its method. I want to return $to_return but the problem is that $to_return does not change even when the function is using 'use' keyword. Here is the function:

function some_function($arg){

    $to_return = false;

    $object = new Object;

    $to_return = $object->METHOD(function($callback) use ($to_return){

        $to_return = $some_var;

    });

    $to_return = $object->runMETHOD("some_arg");

    return $to_return;

}

So, basically:

  • $to_return returned is always false
  • I want some_function to return $some_var
  • In short: how can I make some_function return the object changed inside the object method?


    All you miss is indicating that $to_return should be passed by reference:

    function($callback) use (& $to_return)
    

    Also example of working example on 3v4l: https://3v4l.org/Vfp70

    I'm no internals expert, but long story short primitives are "copied" when you pass them somewhere thus what you were setting in the callback is not transfered outside. Objects, on the other hand, would behave like you expected because pointer to object is passed and original instance is modifed. Using even plain stdClass as such transporter would work, as illustrated in this 3v4l: https://3v4l.org/m9jJ3


    Use the given solution by @malarzm BUT then also don't assign the the function to a $to_return (it has no result anyways)

    So instead of

    $to_return = $object->METHOD(function($callback) use ($to_return)
    

    use:

    $object->METHOD(function($callback) use (&$to_return)
    

    Also you are overwriting the same variable before even using it here:

     $to_return = $object->runMETHOD("some_arg");
    

    So you probably want to assign the return value of that method to a different variable.

    链接地址: http://www.djcxy.com/p/34250.html

    上一篇: 运行大量VBA后打印预览问题

    下一篇: 等待对象实例的php回调函数返回值