Search code examples
phpoopinheritanceprivateredeclare

PHP OOP redeclare private method/function in child class


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:

  1. Overwrite/Redeclare private property function in child class?
  2. Create second function printHello2() in child class when there is one already in parent class, this makes code bit spaghettish isn't it?
  3. Same exact logic apply s to private methods correct?

Solution

  • private is limited to THAT particular class and its code. It is invisble to descendant classes. E.g. if you eliminate the private $private in MyClass2:

    class MyClass2 extends MyClass1 {
        // private $private = 'Private 2';
        ^^---literally the only change
    

    and then run the code:

    Public 2 MyClass1
    Protected 2 MyClass1
    Private 1 MyClass1
    Public 2 MyClass2
    Protected 2 MyClass2
    PHP Notice:  Undefined property: MyClass2::$private in /home/sites/ca.usask.vido-inout/html/z.php on line 25
     MyClass2
    

    That's why you get Private 1 and Private 2. private variables aren't "shared" within the family. You're not "overwriting" anything, because private 1 doesn't exist in the descendant classes.