PHP & OOP: Visibility

The visibility of a property or method can be defined by the keywords public, protected or private.

Property (variable) visibility

Class members declared public can be accessed everywhere.

Members declared protected can be accessed only within the class itself and by inherited and parent classes.

Members declared as private may only be accessed by the class that defines the member.

Lets look at the example below.

<?php

class MyClass
{
    public $public_str = 'I am a public string';
    protected $protected_str = 'I am a protected string';
    private $private_str = 'I am a private string';

    function printString()
    {
        echo $this->public_str . "<br>";

        echo $this->protected_str . "<br>";
        echo $this->private_str . "<br>";
    }
}

$obj = new MyClass();
$obj->printString(); // Shows Public, Protected and Private, pringString() is a public function
echo "<br>";
echo $obj->public_str; // Works
// echo $obj->protected; Fatal Error as $protected is accessed outside the class and not by an inherited class
// echo $obj->private; Fatal Error as $private is accessed outside the class

?>

The 3 member variables $public_str, $protected_str, $private_str can be assessed using the function printString() as it is a member function

printString() is a public function and so you can access it to print out the 3 variables.

$obj->protected_str:  This will produce a fatal error as $protected is accessed outside the class and not by an inherited class

$obj->private_str:  This will generate a fatal error as $private is accessed outside the class.

Series Navigation<< PHP & OOP: Constructors and destructors
PHP & OOP: Method visibility >>