views:

67

answers:

4

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
  }
}
+5  A: 

PHP is not asynchronous. Functions are executed one after another.

Mchl
sometimes it's a blessing, sometimes it's a curse...
pxl
It's a blessing. Trust me, you wouldn't want to be forced to do concurrent programming all the time.
Mchl
A: 

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.

fleces
+1  A: 

PHP isn't threaded, so if you call function1_geocode before function2_proximitysearch, $result should always be set.

Ian Wetherbee
A: 

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.

Jason