我最近一直试图自我教导一些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
作为$foo
类的对象,$bar
中$test2
和NULL
都是$foo
。构造函数肯定在运行 - 如果我在构造函数中回显$bar
和$test1->foo
,它们会显示(使用正确的值,不能少)。然而,尽管它们被var_dump
分配了值,但它们不会通过$test2->bar
或{{1}}显示。有人可以向我解释一下这种善意的好奇心吗?
答案 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;
}