Question

I am trying to sort an array of objects by a shared property, however, I cannot get my $ property parameter to register in an inner function (I can use it in an outer OK).

As I read the documentation, it sounded like the parameter would be available, am I missing something?

Here's 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 is appreciated. Thanks.

+2


a source to share


2 answers


Unfortunately this will not work in php. No nested scope, each function has its own local scope. Also, all functions, no matter where they are declared, are global and can only be declared once, so you will get an error if sortObjectsByProperty is called more than once.

in php5.3 you can work around this using lambdas like



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

      

+7


a source


You cannot inline such functions in PHP. However, you can use 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);
  }
}

      

-1


a source







All Articles