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 falsesome_function
to return $some_varIn short: how can I make some_function return the object changed inside the object method?
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.
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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With