Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 327
Fane Avatar asked May 20 '16 12:05

Fane


People also ask

What is call_ user_ func_ array in PHP?

The call_user_func_array() function is a special way to call an existing PHP function. It takes a function to call as its first parameter, then takes an array of parameters as its second parameter.

How to define callback function in PHP?

In PHP, we can use the call_user_func() function to call functions, where arguments are the function's string name. Example: <? php // Function to callback function my_callback_function() { echo 'Hello, world!

How to specify return type in PHP?

There is no way to define the return type of a function within PHP as it is loosely-typed. You will have to do your validation within the calling function. The bool type was just a example.

Are PHP functions callable?

The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.


1 Answers

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

like image 187
malarzm Avatar answered Oct 21 '22 00:10

malarzm