-2
class FatherClass
{
    private $salary = 10;

    public function showInfo()
    {
        echo $this->phone . '<br/>';
        // why this result is 10
        // why the result is not 20000
        echo $this->salary . '<br/>';
    }
}

class ChildClass extends FatherClass
{
    protected $phone = '13987654321';
    private $salary = 20000;
}

$child = new ChildClass();
$child->showInfo();
echo '<pre>';
print_r($child);

the question of 'private':

why this result is 10

why the result is not 20000

Thanks for your help

web360
  • 15
  • 2

2 Answers2

-2

Because private variables are belongs to the class it declares. So showInfo method can only access to its own class private variable not subclass private variable.

Change variable to public in both class to work as intended.

Jasmin Mistry
  • 1,459
  • 1
  • 18
  • 23
-2

When you declare something as 'private' it means that it's only accessible to other code defined in the same class in the class hierarchy. You can have two private variables defined in a child and parent class with the same name and they won't interfere with each other, as you saw. If you do want a variable that's not accessible outside the class but is accessible by functions in other classes in the class hierarchy, use protected.

Note that if you copy-pasted showInfo into ChildClass unchanged, you'd see 20000.

Yuliy
  • 17,381
  • 6
  • 41
  • 47