属性未由构造函数定义

时间:2012-07-18 21:26:04

标签: 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();

简单的东西。 $test1应该将对象返回$test2$test2->foo等于4,$test2->bar等于16.我的问题是,$test2test2作为$foo类的对象,$bar$test2NULL都是$foo。构造函数肯定在运行 - 如果我在构造函数中回显$bar$test1->foo,它们会显示(使用正确的值,不能少)。然而,尽管它们被var_dump分配了值,但它们不会通过$test2->bar或{{1}}显示。有人可以向我解释一下这种善意的好奇心吗?

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

您应该使用'this'访问您的班级成员:

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