Your background in C ++ led to this problem, which is easy to do. In PHP, all instance (or object) variables refer to the variables $this-> and static (or class) using self:: . Based on your code:
public function GetID() { return $m_nID; }
Access to the private variable $m_nID should be copied as follows:
public function GetID() { return $this->m_nID; }
And inside your constructor:
$m_nID = self::$s_nIDGenerator++;
Must be:
$this->m_nID = self::$s_nIDGenerator++;
Q and A
Why there is no need to set $ to m_nID when using $this->
The above two ways to reference instance and class variables have a completely different kind of syntax:
$this is a reference instance variable, and any properties are accessible using the -> operator; $ not repeated for the property names themselves, although they are present in the declaration (for example, private $myprop ).
self:: is a synonym for Something:: (the class name itself); it does not reference an instance variable and therefore does not have $ in front of it. To distinguish static variables from class constants ( self::MYCONST ) and class methods ( self::myMethod() ), with the $ prefix.
Extra
Thus, $this->$myvar also accepted and works as follows:
private $foo = 'hello world'; function test() { $myvar = 'foo'; echo $this->$foo;
source share