我有以下 PHP 代码来描述颜色。简而言之,我以前使用 PHP 4 的方式,现在正试图让我的头脑在 5.5 左右,所以这是我第一次真正在 PHP 中使用对象。
无论如何,我有一个逻辑错误,我认为这与 Color 类中设置的默认值有关。有人可以解释为什么我的构造函数不起作用,或者发生了什么?
class Color {
private $red = 1;
private $green = 1;
private $blue = 1;
private $alpha = 1;
public function __toString() { return "rgb(" . $this->red . ", "
. $this->green . ", " . $this->blue . ", " . $this->alpha . ")"; }
}
class RGBColor extends Color {
public function __construct($red, $green, $blue) {
$this->red = $red; $this->green = $green;
$this->blue = $blue; $this->alpha = 1;
}
}
class RGBAColor extends Color {
public function __construct($red, $green, $blue, $alpha) {
$this->red = $red; $this->green = $green;
$this->blue = $blue; $this->alpha = $alpha;
}
public function __toString() { return "rgba(" . $this->red
. ", " . $this->green . ", " . $this->blue . ", " . $this->alpha . ")"; }
}
$c = new Color();
echo "Color: " . $c . "<br>";
$c1 = new RGBColor(0.6, 0.4, 1.0);
echo "RGB Color: " . $c1 . "<br>";
$c2 = new RGBAColor(0.6, 0.4, 1.0, 0.5);
echo "RGBA Color: " . $c2 . "<br>";
我得到以下输出...
Color: rgb(1, 1, 1, 1)
RGB Color: rgb(1, 1, 1, 1)
RGBA Color: rgba(0.6, 0.4, 1, 0.5)
当我应该得到...
Color: rgb(1, 1, 1, 1)
RGB Color: rgb(0.6, 0.4, 1.0)
RGBA Color: rgba(0.6, 0.4, 1, 0.5)
谢谢!-科迪