views:

146

answers:

2

Hi, I'm trying to sort an array of objects by a common property, however I cannot get my $property parameter to register in the inner function (I can use it in the outer one OK).

The way I read the documentation, it sounded like the parameter would be available, have I misunderstood something?

Here is what I have:

public static function sortObjectsByProperty($objects, $property)  
  {     
        function compare_object($a, $b) 
        {   
            $a = $a->$property;
            $b = $b->$property;

            if ($a->$property == $b->$property)
            {
                return 0;
            }      

            return ($a->$property > $b->$property) ? +1 : -1;        
        }

        usort($objects, 'compare_object');
        return $objects;
  }

Any advice appreciated. Thanks.

+4  A: 

Unfortunately, this won't work in php. There is no nested scope, each function has its own local scope. Besides that, all functions, no matter where they are declared, are global and can be declared only once, so you'll get an error message if sortObjectsByProperty will be called more than once.

in php5.3 you can work around this by using lambdas, for example

function sortObjectsByProperty($objects, $property)  
{     
        $compare_object = function($a, $b) use($property)
        {   
            $a = $a->$property;
            $b = $b->$property;

            if ($a->$property == $b->$property)
            {
                return 0;
            }      

            return ($a->$property > $b->$property) ? +1 : -1;        
        };

        usort($objects, $compare_object);
        return $objects;
  }
stereofrog
A: 

You can't embed functions like that in PHP. What you can do, though, is make use of a private static function:

class myClass {
  private static function compare_object($a, $b) {
    // do stuff
  }
  public function sortObjectsByProperty($objects, $property) {
    $a = new a();
    $b = new b();
    self::compare_object($a, $b);
  }
}
Stephen J. Fuhry
You can embed functions in functions.
zaf