I've been playing around and seeing if I can set up a more dynamic method in PHP.
usort(
$dataset,
function($a, $b){
return strcasecmp($a[$this->parameters], $b[$this->parameters]);
}
);
This line would sort array elements in alphabetically descending order. However, if we were to swap variables $a and $b whether in function($a, $b) or ($a[$this->parameters], $b[$this->parameters]) we will get the opposite effect (descending order).
As I've looked into the matter, there is such a thing as "variable variables" in PHP. An example of this coulde be:
$a="hello";
$$a="oops";
echo($hello);die;
However, if I similarly try to implement this within the code of line above I get an error.
$first = 'b';
$second = 'a';
usort($dataset, function($$first, $$second){ return strcasecmp($a[$this->parameters], $b[$this->parameters]); });
Error:Parse error: syntax error, unexpected '$', expecting variable (T_VARIABLE).
The idea is to be able to reverse the effect base on an iff statement result to redefine $first and $second variables. Otherwise one would need to duplicate almost identical code.
Am I missing something? Maybe some other way to achieve this?
function(${$first}, ${$second})...(a.k.a. unpack operator) and variadic functions using similar notation. See: wiki.php.net/rfc/variadics & wiki.php.net/rfc/argument_unpacking On a related note, the variable variables are generally a bad idea due to unintended side effect type issues. Anytime you have execution of dynamic code, you should really stop and ask yourself if you can make a better design choice.