Inside php manual example http://php.net/manual/en/language.oop5.visibility.php#example-242 it is saying
We can redeclare the public and protected method, but not private
what do they mean my that i might not be getting how to use inheritance properly but say we have this code.
class MyClass1 {
public $public = 'Public 1';
protected $protected = 'Protected 1';
private $private = 'Private 1';
function printHello1() {
echo $this->public . " MyClass1 ". PHP_EOL;
echo $this->protected . " MyClass1 " . PHP_EOL;
echo $this->private . " MyClass1 " . PHP_EOL;
}
}
class MyClass2 extends MyClass1 {
public $public = 'Public 2';
protected $protected = 'Protected 2';
private $private = 'Private 2';
function printHello2() {
echo $this->public . " MyClass2 ". PHP_EOL;
echo $this->protected . " MyClass2 " . PHP_EOL;
echo $this->private . " MyClass2 " . PHP_EOL;
}
}
$obj2 = new MyClass2();
$obj2->printHello1();
$obj2->printHello2();
will return
Public 2 MyClass1
Protected 2 MyClass1
Private 1 MyClass1
Public 2 MyClass2
Protected 2 MyClass2
Private 2 MyClass2
Seems like i am able to create another $private
variable in MyClass2
without any problem, so why they say its we can't?
yes it does not change $private
variable in MyClass1
when i use function printHello1()
in parent class however when i run printHello2()
in child class MyClass2
it does show new value for $private
variable.
Now question i have is this bad practice to:
- Overwrite/Redeclare private property function in child class?
- Create second function
printHello2()
in child class when there is one already in parent class, this makes code bit spaghettish isn't it? - Same exact logic apply s to private methods correct?