PHP 成员变量默认值


PHP member variable default value

我有以下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)

谢谢! -科迪

这不是初始化顺序的问题,而是可见性的问题。私有变量只能通过同一类中定义的方法访问。 Color::__toString()访问Color上定义的变量,但子类中的构造函数访问子类上的不同变量。举个简单的例子:

<?php
class A {
    private $p = __CLASS__;
}
class B extends A {
    function __construct() {
        $this->p = __CLASS__;
    }
}
$b = new B;
var_dump($b);

输出:

类 B#1 (2) {  私人$p =>  字符串(1) "A"  公共$p =>  字符串(1) "B"}

如果希望成员变量在后代中可访问,请使其受保护而不是私有。

对要在子类上使用的变量使用受保护的 not private。另一种方法是编写二传手和getter。

我猜可能是int和float问题,似乎PHP将其四舍五入为整数。