Reputation: 3763
I've been trying to self-teach some OOP lately, and I came across something which seems curiously strange to me. I was wondering if someone can explain this to me.
I was inspired by one of the questions on this site to try out this little test piece of code (in 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();
Simple stuff. $test1
should return back an object to $test2
, with $test2->foo
equal to 4 and $test2->bar
equal to 16. My problem with this is that, while $test2
is being made into an object of class test2
, both $foo
and $bar
within $test2
are NULL
. The constructor function is definitely being run - if I echo $foo
and $bar
in the constructor function, they show up (with the right values, no less). Yet, despite them being assigned values by $test1->foo
, they don't show up either through the var_dump
or through $test2->bar
. Can someone explain this bit of intellectual curiosity to me?
Upvotes: 1
Views: 66
Reputation: 2908
You should access you class members with 'this':
function __construct ($x, $y) {
$this->foo = $x;
$this->bar = $y;
}
Upvotes: 2
Reputation: 91742
Your syntax is wrong, it should be:
class test2 {
public $foo;
public $bar;
function __construct ($x, $y) {
$this->foo = $x;
$this->bar = $y;
}
function bar () {
echo $this->foo, $this->bar;
}
}
Upvotes: 5