PHP 使用命名空间传递参数[重复]

问题描述 投票:0回答:1
namespace App\Controllers\Redis;

class getArray{
  public function sortArray(){
   $sortMe = Array
   (
    '05' => 100,
    '15' => 1,
    '24' => 10,
    '32' => 1000,
   );

   $sorted= Array
   (
    '0' => 1,
    '1' => 10,
    '2' => 100,
    '3' => 1000,
   );
   function cmp($a, $b) {
    //I need to get $sorted here
    return array_search($a, $sorted) - array_search($b, $sorted);
  }
  usort($sortMe , 'App\Controllers\Redis\cmp');//pass the $sorted parameter
}
}

如何传递带有名称空间的数组参数,因为我发现的所有其他引用都没有名称空间,所以我迷失了。感谢任何建议。

我尝试过的:

private $sorted = []; //declace a private var in the class

$this->sorted= Array
(
    '0' => 1,
    '1' => 10,
    '2' => 100,
    '3' => 1000,
);

function cmp($a, $b) {
  $sorted = $this->sorted;
  return array_search($a, $sorted) - array_search($b, $sorted);
}

但这将返回 PHP 错误:PHP 致命错误:未捕获错误:不在对象上下文中时使用 $this

PHP 编辑器链接:

预期结果:https://3v4l.org/gbbua#v7.0.14

我当前的程序:https://3v4l.org/1Kmoq#v7.0.14

php usort
1个回答
0
投票

命名空间或类与这里的任何内容都没有什么关系。你只想要一个匿名回调:

$sortMe = array(...);
$sorted = array(...);

usort($sortMe , function ($a, $b) use ($sorted) {
    return array_search($a, $sorted) - array_search($b, $sorted);
});
© www.soinside.com 2019 - 2024. All rights reserved.