PHP函数不从多维数组返回值

时间:2018-04-15 02:03:19

标签: php function multidimensional-array return-value undefined-variable

我一直致力于调色板系统,其中多维数组包含不同的调色板。 EX:

$palette['1']['borderColor'] = "black";
$palette['2']['borderColor'] = "white";

我有一个函数应该在调用时返回一个调色板项,但由于某种原因它没有返回任何东西。相反,它说"未定义的变量:palette" EX:

$palette['1'] = array(
    "borderColor"=> "#222222",
    "divColor1"=> "#00f2ff",
    "divColor2"=> "#222222",
    "headerColor"=> "rgba(38, 38, 38, 0.5)",
    "color1"=> "#00f2ff",
    "color2"=> "#e9ffdd"
  );

function getItem($number, $item) {
  return $palette[$number][$item];
}

$borderColor = getItem('1', 'borderColor');
echo "borderColor is> " . $borderColor . " <.";

//returns "borderColor is>  <."

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您编写的函数没有实际的调色板值。只需将您想要的调色板传递给函数。

$palette['1'] = array(
    "borderColor"=> "#222222",
    "divColor1"=> "#00f2ff",
    "divColor2"=> "#222222",
    "headerColor"=> "rgba(38, 38, 38, 0.5)",
    "color1"=> "#00f2ff",
    "color2"=> "#e9ffdd"
  );

function getItem($palette, $number, $item) {
  return $palette[$number][$item];
}

$borderColor = getItem($palette,'1', 'borderColor');
echo "borderColor is> " . $borderColor . " <.";

另一种方法是创建一个可以调用调色板的简单类。

class Palette {

  public function __construct($palette){

  $this->borderColor  = $palette['borderColor'];
  $this->divColor1    = $palette['divColor1'];
  $this->divColor2    = $palette['divColor2'];
  $this->headerColor  = $palette['headerColor'];
  $this->color1       = $palette['color1'];
  $this->color2       = $palette['color2'];

  }


}

$palette['1'] = array(
    "borderColor"=> "#222222",
    "divColor1"=> "#00f2ff",
    "divColor2"=> "#222222",
    "headerColor"=> "rgba(38, 38, 38, 0.5)",
    "color1"=> "#00f2ff",
    "color2"=> "#e9ffdd"
  );

$black = new Palette($palette['1']);
$white = new Palette($palette['2']);

echo $black->borderColor;
echo $white->borderColor;

答案 1 :(得分:2)

实际上在你的getItem函数中,变量 $ palette 不可用,所以你要在 getItem 函数上传递它,或者只是添加 global $ palette 变量中的strong>关键字。

方式1:

function getItem($palette, $number, $item) {
  return $palette[$number][$item];
}

$borderColor = getItem($palette,'1', 'borderColor');

方式2:

function getItem($number, $item) {
  global $palette; // it will be available here
  return $palette[$number][$item];
}

$borderColor = getItem('1', 'borderColor');

DEMO https://eval.in/988491