I have a simple function1 that does a http request to a google api and returns the $result. I then have another function2 that, if $result isset, should use $result to do some computing and then return $finalresult. .
My problem is that the call to the google api takes a couple of seconds and by the time $result is returned by function1, function2 has already returned $finalresult without taking into consideration $result.
What I am looking to do is to have function1 to run completely and return $result before function2 even begins.
Preferrably I am looking for a solution that is not simply using "sleep()" as this function will not guarantee that $result is actually returned. (Unless there is some way to loop a sleep(1) until $return isset, or something like that)
Sample code for the visual开发者_高级运维 gals and guys
function1_geocode($address); // this function makes a http request to google and returns $result
function2_proximitysearch(){
if (isset($result)){
//inevitably by the time the script gets there, $result hasn't been returned yet therefore none of the "some stuff" code is executed.
//some stuff
}
else {
//some other stuff
}
}
PHP is not asynchronous. Functions are executed one after another.
why don't you have function 1 call function 2 when it is done?
additionally, Mchl is right. function 1 will have to complete before the code executes function 2. Maybe you should set up your code like so:
$foo = 0;
$foo = function1();
if($foo > 0)
function2();
function1()
{
if($something)
$foo = 1;
}
function2()
{
$something = $else;
}
That way it will only call function 2 if function 1 changed the value of $foo.
Of you could post your full code and we'll know what you're trying to do.
PHP isn't threaded, so if you call function1_geocode
before function2_proximitysearch
, $result
should always be set.
It could be that function1_geocode($address) has a bug, or else you might be missing some documentation for how that function is used.
It's possible to kinda simulate asynchronous functionality by, for example saving results in a file to be dealt with by a second page load. But that would have to be specifically designed that way. Within one PHP page load, you can't have a process running in the background.
精彩评论