Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 1.67 KB

2.md

File metadata and controls

51 lines (39 loc) · 1.67 KB

Lesson 2: Visibility

New keywords
  • public
  • private
  • protected

Visibility

One interesting thing to note is that each method and property can have an associated level of visibility, which enables information-hiding. The three types of visibility are public, private, and protected.

  • Public properties are ones that directly accessible in the instantiated object.
  • Private properties cannot be accessed anywhere except from within the class. This allows one to create a public interface, where some critical internal state can be protected.
  • We will discuss the protected visibility later as it's dependent upon understanding inheritance.

Any methods created without a specific declared visibility default to public. Keep in mind that properties must be declared public, private, or protected, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value (must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated).

<?php

class Person {
  private $name;

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$person = new Person();
$person->name = 'error'; // This will error out because it's a private property
$person->setName('Alice');
echo $person->getName(); // Alice

Exercises

  1. Expand the previous “Person” class, add setName(), getName() methods.
  2. Add a height property, and a getter and setter.
  3. Declare the correct “visibility” for each property and method.
  4. Invoke var_dump() on the person object to inspect it.