Creative crypter
Creative crypter

Reputation: 1496

Call class method by string name as callback of a native function within another class method

I know this question has been asked before, but not in this context (OOP):

class XYZ {

    public function index() {

        $array = [
            [
                'id' => 1,
                'name' => 'Alpha'
            ],
            [
                'id' => 2,
                'name' => 'Beta'
            ],
            [
                'id' => 3,
                'name' => 'Gamma'
            ]
        ];

        $newArray = usort($array, 'modify');

        return $newArray;

    }

    public function modify($a, $b) {

        return $b['name'] - $a['name'];

    }

}

This indexAction returns an empty array, and I am not sure why.

Upvotes: -1

Views: 471

Answers (3)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Over here within your usort function the second parameter consist of two values first one ClassName and the other one functionName so your second parameter looks like as

usort($array,['ClassName','functionName']);

Which in your case it'll be like as

usort($array,['XYZ','modify']);

Demo

Upvotes: 1

Gowtham Raj
Gowtham Raj

Reputation: 2955

ksort — Sort an array by key

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange b = banana c = apple d = lemon

For more info : http://php.net/manual/en/function.ksort.php

Upvotes: 3

Amarnasan
Amarnasan

Reputation: 15529

Because usort returns a boolean http://php.net/manual/en/function.usort.php . You want to return the modified variable $array

Upvotes: 1

Related Questions