Sheraz Ahmed
Sheraz Ahmed

Reputation: 899

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?

Upvotes: 1

Views: 3399

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

A closure is an object that can be called like a function. As you can see from the output, when you use $lat in print_r($lat);, it is not the result of calling the closure, it is the closure object itself. (Defined by $lat = function () {... - see example 2 in the PHP documentation for anonymous functions), . If you want to get that result, you have to call it with (), just like any normal function call.

print_r($lat());

As it is currently, the closures aren't really necessary, but for an example of how to define and use a closure, you could do like this to eliminate the repeated code:

// assign the anonymous function to $coord
$coord = function($a, $b) {
    $float = rand(0, 99999) / 99999;
    $coord = rand($a, $b);
    return $coord + $float;
};

for ($i = 0; $i < 10; $i++) {
    // use $coord to generate coordinates for a point
    $point = [$coord(30, 32), $coord(74, 76)];
    var_dump($point);
}

Upvotes: 1

segFault
segFault

Reputation: 4054

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);
}

Upvotes: 1

Related Questions