usort function in a class
I have a function which sorts data in a multidimensional array, as shown below:
<?php
$data = array();
$data[] = array("name" => "James");
$data[] = array("name" => "andrew");
$data[] = array("name" => "Fred");
function cmp($a, $b)
{
return strcasecmp($a["name"], $b["name"]);
}
usort($data, "cmp");
var_dump($data);
?>
When i run this, it works as expected, returning the data ordered by name, ascending. However, I need to use this in a class.
<?php
class myClass
{
function getData()
{
// gets all data
$this -> changeOrder($data);
}
function changeOrder(&$data)
{
usort($data, "order_new");
}
function order_new($a, $b)
{
return strcasecmp($a["name"], $b["name"]);
}
}
?>
When I use this, i get the following warning: Warning: usort() expects parameter 2 to be a valid callback, function 'order_new' not found or invalid function name.
When i put the order_new function in the changeOrder function it works fine, but I have problems with Fatal error: Cannot redeclare order_new(), so i cannot use that. Any suggestions?
order_new is a class method not a global function. As the PHP-Manual suggest you can use in this case
usort($data, array($this, "order_new"));
or declare order_new static and use
usort($data, array("myClass", "order_new"));
Change to usort($data, array($this, "order_new"));
usort($data, array($this,"order_new"));
is what you want when referring to a function in your class instance. See callable
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
One thing to consider is that if the variable is passed to your method by reference, usort() appears to execute in the context of the referenced variable and not your current method. Therefore, you need to provide the full namespace in your class reference like so:
usort($data, ['My\NameSpace\MyClass', 'order_new']);