There are three visibility types that you can apply to methods (class/object functions) and properties (class/object variables) within a class, which provide access control for the method or property to which they are applied.

You can read extensively about these in the PHP Documentation for OOP Visibility.

Public

Declaring a method or a property as public allows the method or property to be accessed by:

An example of this public access would be:

class MyClass {
    // Property
    public $myProperty = 'test';

    // Method
    public function myMethod() {
        return $this->myProperty;
    }
}

$obj = new MyClass();
echo $obj->myMethod();
// Out: test

echo $obj->myProperty;
// Out: test

Protected

Declaring a method or a property as protected allows the method or property to be accessed by:

This does not allow external objects, classes, or code outside the class hierarchy to access these methods or properties. If something using this method/property does not have access to it, it will not be available, and an error will be thrown. Only instances of the declared self (or subclasses thereof) have access to it.

An example of this protected access would be:

class MyClass {
    protected $myProperty = 'test';

    protected function myMethod() {
        return $this->myProperty;
    }
}

class MySubClass extends MyClass {
    public function run() {
        echo $this->myMethod();
    }
}

$obj = new MySubClass();
$obj->run(); // This will call MyClass::myMethod();
// Out: test

$obj->myMethod(); // This will fail.
// Out: Fatal error: Call to protected method MyClass::myMethod() from context ''

The example above notes that you can only access the protected elements within it’s own scope. Essentially: “What’s in the house can only be access from inside the house.”


Private