I have the following code: Class definition:
<?php class Person{ var $name; public $height; protected $socialInsurance = "yes"; private $pinnNumber = 12345; public function __construct($personsName){ $this->name = $personsName; } public function setName($newName){ $this->name = $newName; } public function getName(){ return $this->name; } public function sayIt(){ return $this->pinnNumber; } } class Employee extends Person{ } And the part with instances:
<!DOCTYPE html> <HTML> <HEAD> <META charset="UTF-8" /> <TITLE>Public, private and protected variables</TITLE> </HEAD> <BODY> <?php require_once("classes/person.php"); $Stefan = new Person("Stefan Mischook"); echo("Stefan's full name: " . $Stefan->getName() . ".<BR />"); echo("Tell me private stuff: " . $Stefan->sayIt() . "<BR />"); $Jake = new Employee("Jake Hull"); echo("Jake's full name: " . $Jake->getName() . ".<BR />"); echo("Tell me private stuff: " . $Jake->sayIt() . "<BR />"); ?> </BODY> </HTML> Output:
Stefan's full name: Stefan Mischook. Tell me private stuff: 12345 Jake's full name: Jake Hull. Tell me private stuff: 12345 // Here I was expecting an error As I understand, the private variable is accessible only from it's own class, and the protected variable is accessible also from the classes that extend the class. I have the private variable $pinnNumber. So I expected, that I get an error if I call $Jake->sayIt(). Because $Jake is member of class Employee that extends class Person. And the variable $pinnNumber should be accessible only from class Person, not from the class Employee.
Where is the problem?
$pinnNumberin the class employee? You're accessingsayIt()which is public thus callable.Employeeinherited fromPerson.Employeedidn't directly access theprivatevariable. It used a method that comes from parent class (it was inherited), and that parent class is allowed to access the variable. Therefore, it's all good.