最近我一直在尝试自我教导一些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
是NULL
对象返回到$test2
,与$test2->foo
等于4并且$test2->bar
等于16我的这一问题是,虽然$test2
被制成test2
类的一个对象,既$foo
和$bar
。构造函数肯定正在运行 - 如果我在构造函数中回显$foo
和$bar
,它们将显示出来(使用正确的值,不会少于)。然而,尽管他们被分配了$test1->foo
的值,但他们不会通过var_dump
或$test2->bar
显示出来。有人能向我解释这种对知识的好奇吗?
$这个 - >富= $ X; $ this-> bar = $ y;在构造函数中;和功能栏(){ echo $ this-> foo,$ this-> bar; }否则$ foo和$ bar只是局部范围变量 – 2012-07-18 21:28:50
可能重复的[PHP变量在类中](http://stackoverflow.com/questions/1292939/php-variables-in-classes) – Gordon 2012-07-18 21:37:06