我正在尝试编辑一个具有DB驱动结果的类。我通过代码世界( Code )使用ColorInterpreter,它是JavaScript库NTC的一个PHP端口。
这个类中有一个公共变量,它是十六进制/彩色名称对的数组。这是硬编码到类中。我想通过使用DB输出来实现这种动态。
我还在纠结于上课,所以我无法理解这件事。
colornames.inc.php:输出如下所示:
Array
(
[b0bf1a] => Acid Green
[7cb9e8] => Aero
[c9ffe5] => Aero Blue
[b284be] => African Violet
[00308f] => Air Force Blue (USAF)
[72a0c1] => Air superiority Blue
...
}ColorInterpreter.php
class ColorInterpreter
{
public function __construct()
{
$color = null;
$rgb = null;
$hsl = null;
$name = null;
for($i = 0; $i < count($this->names); $i++)
{
$color = "#".$this->names[$i][0];
$rgb = $this->rgb($color);
$hsl = $this->hsl($color);
array_push
(
$this->names[$i],
$rgb[0],
$rgb[1],
$rgb[2],
$hsl[0],
$hsl[1],
$hsl[2]
);
}
}
public function name($color)
{
...
}
// adopted from: Farbtastic 1.2
// http://acko.net/dev/farbtastic
public function hsl($color)
{
...
}
// adopted from: Farbtastic 1.2
// http://acko.net/dev/farbtastic
public function rgb($color)
{
...
}
public function color($name)
{
...
}
// Below is the part I need to replace with the output given from colornames.inc.php
public $names = array(
// Pink colors
array("FFC0CB", "Pink"),
array("FFB6C1", "Light Pink"),
array("FF69B4", "Hot Pink"),
array("FF1493", "Deep Pink"),
array("DB7093", "Pale Violet Red"),
array("C71585", "Medium Violet Red"),
array("E0115F", "Ruby"),
array("FF6FFF", "Ultra"),
...
);
}我不知道如何、是否或应该包含colornames.inc.php,也不知道在哪里正确声明所需的变量。显然,$ this ->name表示硬编码数组,但是如何更改它以反映我的DB输出?我在这里完全迷路了。
发布于 2020-05-31 15:06:30
最好的选择是创建一个返回值的函数,然后在创建类时将其作为构造函数传递。例如:
include 'file_with_function.php';
include 'file_with_class.php';
$initialColorValues = my_get_color_values();
$newObject = new ColorObject($initialColorValues);现在,您可以在构造函数中处理该数组,并且有一个带有正确颜色值的对象。
class XYZ {
public $names;
public function __construct($names){
// ... do work
$this->names = $work;
}
}https://stackoverflow.com/questions/62117256
复制相似问题