PHP public protected private

PHP access modifier public, protected and private to make the access control of property or method.

Access Control

The type of access modifier allows the developer to control access to class members, which is a feature of the OOP language.

PHP supports the following three access modifiers:

  1. public(public): Members of the class will have no access restrictions, and all external members will have access to(read and write) this class member(including member properties and member methods). If a member of a class does not specify a member access modifier, it is treated as public.
  2. protected(protected): A member defined as protected can not be accessed by external code for that class, but a subclass of that class has access.
  3. private(private): members defined as private, allowing access to all members of the same class, but not for external code and subclasses of that class.
public protected private
in the same class
Subclass of the class
all external members


When a subclass overrides a method of a superclass, the access of the method in the subclass can not be less than the access of the superclass's overridden method.


Encapsulation, is the class(object) attributes and services into a separate unit, and as much as possible to hide the details of the internal, leaving only the necessary interface with the external contact. This package features an effective guarantee of the independence of the object, so that software errors can be localized, greatly reducing the difficulty of troubleshooting and troubleshooting.

Use the private keyword to encapsulate properties and methods:

class Person {
    // Define member properties as private
    private $name;
    private $age;

    // Define a constructor initialization assignment
    function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;

    function say() {
        echo "My name is: ". $this->name. "<br />";
        echo "My age is: ". $this->age;

$p1 = new Person("David", 20);

In this example, if we try to use $p1->name = "David"; this way to access the object properties will produce an error. The constructor and say() method does not specify a private property, in PHP is the default public(public).

Copyright 2014-2017 by All Rights Reserved.