PHP OOP how to access the parent property of a class. Scope Permission operator (: :)?
How can I access a property var
in a class OtherClass
from an inner class like a methodmyFunc (parent::myFunc();)
<?php
class MyClass
{
public $var = 'A';
protected function myFunc()
{
echo "MyClass::myFunc()\n";
}
}
class OtherClass extends MyClass
{
public $var = 'B';
// Override parent definition
public function myFunc()
{
// But still call the parent function
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}
$class = new OtherClass();
$class->myFunc();
source to share
You cannot, because there is no separate variable. OtherClass
extends MyClass
therefore OtherClass
contains all the functions of MyClass + additional stuff from OtherClass
, but while maintaining access to parent methods (via parent::
) makes sense (i.e. allows chaining) and then having more than one variable with the same name can cause massive headache without any- or benefits.
source to share
Create getter and setter methods for var.
class MyClass
{
private $var = 'A';
public function getVar()
{
return $this->var;
}
public function setVar($var)
{
$this->var = $var;
}
protected function myFunc()
{
echo "MyClass::myFunc()\n";
}
}
Then you can use $this->getVar()
in OtherClass
if you don't override getters and setters there. Or if you do, you can use parent::getVar()
from OtherClass
.
source to share