构造函数未定义属性


Properties not being defined by constructor

我最近一直在尝试自学OOP,我发现了一些奇怪的东西。我想知道是否有人能向我解释一下。

我受到这个网站上一个问题的启发,尝试了这段小测试代码(用PHP):

class test1 {
    function foo ($x = 2, $y = 3) {
    return new test2($x, $y);
    }
}
class test2 {
    public $foo;
    public $bar;
    function __construct ($x, $y) {
        $foo = $x;
        $bar = $y;
    }
    function bar () {
        echo $foo, $bar;
    }
}
$test1 = new test1;
$test2 = $test1->foo('4', '16');
var_dump($test2);
$test2->bar();

简单的东西。$test1应该向$test2返回一个对象,其中$test2->foo等于4,$test2->bar等于16。我的问题是,当$test2被制成类test2的对象时,$test2中的$foo$bar都是NULL。构造函数肯定在运行——如果我在构造函数中回显$foo$bar,它们就会显示出来(具有正确的值)。然而,尽管它们被$test1->foo赋值,但它们并没有通过var_dump$test2->bar出现。有人能向我解释一下这种求知欲吗?

您的语法错误,应该是:

class test2 {
    public $foo;
    public $bar;
    function __construct ($x, $y) {
        $this->foo = $x;
        $this->bar = $y;
    }
    function bar () {
        echo $this->foo, $this->bar;
    }
}

您应该使用"this"访问类成员:

function __construct ($x, $y) {
    $this->foo = $x;
    $this->bar = $y;
}