🎓 A1Learner
🔍
0 of 38 lessons completed

Visibility in Depth

Visibility in depth is the study of how far a member can be reached from each place in a program. The three levels are public, private and protected, and a member is one property or method of a class.

A protected property read by a child method

The owner property in Account is protected. The Savings child reads it inside its own method and prints it.

<?php
class Account {
  protected $owner = "Hana";
}
class Savings extends Account {
  public function showOwner() {
    echo "Owner: " . $this->owner . "\n";
  }
}
$savings = new Savings();
$savings->showOwner();

A private property is not shared

Vault and Safe each declare a private code with a different value. The parent method prints the parent value, and the child method prints the child value.

<?php
class Vault {
  private $code = "1111";
  public function vaultCode() {
    echo "Vault code: " . $this->code . "\n";
  }
}
class Safe extends Vault {
  private $code = "2222";
  public function safeCode() {
    echo "Safe code: " . $this->code . "\n";
  }
}
$safe = new Safe();
$safe->vaultCode();
$safe->safeCode();

Reading a protected property from outside fails

This program reads the protected owner property from outside any class. PHP stops with a fatal error, and the line below states that error.

<?php
class Account {
  protected $owner = "Hana";
}
$account = new Account();
echo $account->owner, "\n";

Example

<?php
class Account {
  private $pin = "2468";
  protected $owner = "Hana";
  public function checkPin($pin) {
    if ($pin === $this->pin) {
      echo "Pin accepted\n";
    } else {
      echo "Pin refused\n";
    }
  }
}
class Savings extends Account {
  public function showOwner() {
    echo "Owner: " . $this->owner . "\n";
  }
}
$savings = new Savings();
$savings->showOwner();
$savings->checkPin("2468");
$savings->checkPin("0000");

Key points

  • A protected member can be reached inside its class and inside child classes.
  • A private member can be reached only inside the class that declares it.
  • A child class does not share the private members of its parent.
  • A child can declare a private member with the same name, and it stays separate from the parent one.
  • Reading a protected member from outside stops the program with a fatal error.
  • Public methods are the door through which outside code uses private and protected data.

In this example, Account keeps its pin private and its owner protected. The Savings child reads the owner through its own method. The pin is checked only by the public checkPin method of the parent, which accepts the right pin and refuses the wrong one.

Note

A child class may widen a member it takes, and it may never narrow one.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A child class declares a private property with the same name as a private property in its parent. Which value does a parent method read?