属性未由构造函数定义

Pal*_*ium 1 php oop

我最近一直在努力自学一些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();
Run Code Online (Sandbox Code Playgroud)

简单的东西.$test1应返回回一个目的是$test2,以$test2->foo等于4并且$test2->bar等于16我的这一问题是,虽然$test2被做成类的一个对象test2,既$foo$bar$test2NULL.构造函数肯定是在运行 - 如果我回显$foo$bar在构造函数中,它们会显示(使用正确的值,不能少).然而,尽管他们被赋予了价值$test1->foo,但他们并没有通过var_dump或通过$test2->bar.有人可以向我解释这一点的求知欲吗?

jer*_*oen 5

你的语法错了,它应该是:

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