GeeK GeeK - 2 months ago 8
PHP Question

PHP Closure Object

I am trying to generate lat and long cordinates for about a 1000+ locations, I know how to get them in a range and everything but I was wondering if I can do something like this.

for ($i = 0; $i < 10; $i++) {
$lat = function () {
$float = rand(0, 99999) / 99999;
$lat = rand(30, 32);
$lat = $lat + $float;
return $lat;
};
$long = function () {
$float = rand(0, 99999) / 99999;
$long = rand(74, 76);
$long = $long + $float;
return $long;
};
print_r($lat);
}


The code didn't throw the desired result instead, I'm getting

closureObject()


There's no error but I can't seem to get it to work, any help would be wonderful, I've tried reading the documentation but doesn't explain anything related to this.

Can this work?

Answer

You need to actually call the Closure function you defined like: echo $lat(); If that is what you are trying to do.

As others have mentioned you could define a function the traditional php way. Something like:

function getCoord($min, $max) {
    $float = rand(0, 99999) / 99999;
    $coord = rand($min, $max);
    $coord = $coord + $float;
    return $coord;
}

for ($i = 0; $i < 10; $i++) {
    echo "Lat: " . getCoord(30, 32) . " Long: " . getCoord(74, 76);
}