Object Oriented

Visibility

PHP

 

Visibility

PHP 5
class Person {
  
  public $name;
  protected $fingerprint;
  
  private function debug() {}
  
}

Access Modifiers are an added control over properties and methods to specify from where they can be accessed.

There are 3 keywords in PHP to specify visibility:

  • public
  • protected
  • private
 

Public

PHP 5
class Person {
  
  // ...
  
  public $name;
  
  public function greet() {
    print("Hi! I'm " . $this->name);
  }
  
}

public properties and methods can be accessed from:

  • Anywhere outside of a class which they are declared
  • Within the class that they are declared
  • From any class inheriting the current class they are declared in.

The default visibility of a property or method is public, if it is not specified.

 

Protected

PHP 5
class Person {
  
  // ...
  
  protected $figerprint;
  
  protected function setFingerprint($fingerprint) {
    $this->fingerprint = $fingerprint;
  }
  
}

protected properties and methods can be accessed from:

  • Within the class that they are declared
  • From any class inheriting the current class they are declared in.

So if Teacher class inherits from Person, then it has access to $fingerprint property and setFingerprint() method.

 

Private

PHP 5
class Person {
 
  // ...
  
  private $person_id;
    
  private function debug() {
    print('person_id: ' . $this->person_id);
  }
  
}

private properties and methods can be accessed from:

  • Within the class that they are declared

So if Teacher class inherits from Person, then it can't read or set the $person_id property or call debug() method from a Person class.