我一直在研究一个调色板系统,其中多维数组包含不同的调色板。前任:
$palette['1']['borderColor'] = "black";
$palette['2']['borderColor'] = "white";
我有一个函数,它在调用时应该返回一个调色板项目,但由于某种原因它没有返回任何内容。相反,它说"未定义的变量:调色板"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> <."
有什么建议吗?
您编写的函数没有实际的调色板值。只需将所需的调色板传递到函数中即可。
$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;
实际上在你的getItem函数中,变量$palette不可用,所以你必须在getItem函数上传递它,或者只是在函数的$palette变量上添加全局关键字。
方式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');
演示 https://eval.in/988491