我最近一直在尝试自学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;
}