2012-07-18 138 views
1

最近我一直在尝试自我教导一些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应该内$test2NULL对象返回到$test2,与$test2->foo等于4并且$test2->bar等于16我的这一问题是,虽然$test2被制成test2类的一个对象,既$foo$bar。构造函数肯定正在运行 - 如果我在构造函数中回显$foo$bar,它们将显示出来(使用正确的值,不会少于)。然而,尽管他们被分配了$test1->foo的值,但他们不会通过var_dump$test2->bar显示出来。有人能向我解释这种对知识的好奇吗?

+4

$这个 - >富= $ X; $ this-> bar = $ y;在构造函数中;和功能栏(){ echo $ this-> foo,$ this-> bar; }否则$ foo和$ bar只是局部范围变量 – 2012-07-18 21:28:50

+0

可能重复的[PHP变量在类中](http://stackoverflow.com/questions/1292939/php-variables-in-classes) – Gordon 2012-07-18 21:37:06

回答

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

哇,这是粗心的我的。谢谢! – Palladium 2012-07-18 21:28:19

+0

@钯:jeroen说得对。不要忘记接受他的回答。 – 2012-07-18 21:32:13

2

你应该访问你的类成员 '这个':

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