-1

For example:

<?php 

class animal {  
  private $property = "animal";
  public function whoami() {
    return "I am an " . $this->property . ".\n";
  }
}

class emu extends animal {
  private $property = "emu";
}

$emu = new emu;
echo $emu->whoami(); // "I am an animal" 

The above code will report "I am an animal", but I would like it to report "I am an emu", without needing to override the whoami() method.

Is there any way of doing this in PHP?

ryrye
  • 9
  • 2
  • 3
    `private` properties can only be accessed by the class that defines the property. I think `protected` is what you are after here. See https://www.php.net/manual/en/language.oop5.visibility.php – cOle2 Feb 02 '21 at 19:34
  • Yes, that's it, thank you @cOle2 - and a public property works too, but then it's public of course. – ryrye Feb 02 '21 at 19:41
  • A general rule of thumb when dealing with inheritance: if both the parent and the child class have a private property or method of the same name, then it should *not* be private. It should be protected. – El_Vanja Feb 02 '21 at 20:08

2 Answers2

0

As answered by @cOle2 in a comment above:

private properties can only be accessed by the class that defines the property. I think protected is what you are after here. See php.net/manual/en/language.oop5.visibility.php

ryrye
  • 9
  • 2
0

You can create getters and setters to access and Modify the attribute. One solution would be this:

 class animal {  
  private $property;

  public function getAnimal() {
      return $this->property;
  }

  public function setAnimal($animal) {
    $this->property = $animal;
  }

  public function whoami() {
    return "I am an " . $this->getAnimal() . ".\n";
  }
}

class emu extends animal {
    public function __construct() {
        parent::setAnimal("Emu");
    }
}

$emu = new emu();
echo $emu->whoami();