I was going through a tutorial and found the programmer writing $this->foo = $bar while declaring a property inside a class. Why not just $foo? What is the difference?
-
1It's the difference between setting up a new variable and assigning something to an existing one. – Obsidian Age Feb 21 '18 at 01:32
-
I know what $this means actually. My question is different. Why is he using $this while declaring a property? Couldn't he just write (visibility) $foo = $var as he is declaring the property, not using it? – RP McMurphy Feb 21 '18 at 01:40
-
`$this->foo` is an object property, `$foo` is a local variable. – Sammitch Feb 21 '18 at 01:50
1 Answers
In answer to the OP, yes, you may initialize a propety directly as I do with respect to $baz. Consider the following code:
<?php
class Test {
private $foo;
private $baz = "okay";
public function __construct() {
$this->foo = 'bar';
}
public function getFoo(){
$foo = "fooey";
return $this->foo;
}
public function getBaz(){
return $this->baz;
}
public function DoSomething(){
echo $foo; // raises an error message
echo $this->getFoo(),"\n";
echo $this->getBaz();
}
}
$t = new Test();
$t->DoSomething();
See live code
The method getFoo() is able to access a private property named $foo which is set by the constructor function. On the other hand, getFoo() has a variable named $foo and that is only accessible because the method chooses to append its value in the return result. Also, $foo in getFoo() is local to that method. As long as one uses the method getFoo(), the private property is accessible even in another method. If you look at the live code, you'll note that an error occurs because method DoSomething() is unable to access the variable $foo in method getFoo(). While you may directly initialize a property, usually it is preferable to do so in the constructor function and there you would need to use $this
.

- 3,797
- 2
- 27
- 33
-
That's exactly my question was. Apparently, I'll have to use $this if I want my variable to be accessible outside the method or declare it at the top or inside the constructor function. Thanks. – RP McMurphy Feb 21 '18 at 02:24
-
1@RPMcMurphy Happy to help. Another way to think of a class property is to call it a member variable of a class..Also, note that if you declare your properties in the constructor, they will all be public. – slevy1 Feb 21 '18 at 09:06