You cannot access property without specifying its scope. If you refer to it by its name, you are referring to a local variable.
To access properties you need to use ->
(Object Operator). Static properties are accessed using the ::
(Double Colon; also called Paamayim Nekudotayim).
If you would like to access a property inside of a class method you would use either of these two operators in connection with scope keyword. To access the scope of the current object within one of its methods, you can use the pseudo-variable $this
. For static properties, you would use self
or static
to refer to the current class. To access the parent class, you would use parent
. Combining all of it:
class B{
static protected $s1;
}
class A extends B {
protected $v1 = 'foo';
static protected $s1;
static private $s2;
public function __construct()
{
print_r($this->v1);
print_r(parent::$s1);
print_r(self::$s1);
print_r(static::$s2);
}
}
For more information, see: PHP: self:: vs parent:: with extends
However, nothing stops you from creating new local variables inside class methods.
class C {
private $var1 = 'bar';
public function func() {
$var1 = 'foo';
print_r($var1); // This is 'foo' not 'bar'
}
}
It all comes down to the scope in which the variable resides. You have different operators and keywords for each scope resolution, but you can create local variables as you would anywhere else in the code.