Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 1.44 KB

2.md

File metadata and controls

42 lines (32 loc) · 1.44 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. There are three types visibility a property can have are public, private, and protected. Public properties are ones that directly accessible by 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. Notes: Any methods created without a specific declared visibility default to public. Keep in mind that all non-method properties must be declared public, private, or protected.

<?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.