PHP - Visibility

Visibility in PHP refers to the concept of controlling the access and visibility of class members (properties and methods) from different parts of your code. PHP provides three main visibility modifiers: public, protected, and private. These modifiers determine where and how class members can be accessed. Here's how visibility works in advanced PHP:

Public (public):

Public members are accessible from anywhere, both within and outside the class.

They can be accessed directly using the object instance or the class name followed by the scope resolution operator (::).

class MyClass {

    public $publicProperty;

    public function publicMethod() {

        // Code here

    }

}

$obj = new MyClass();

$obj->publicProperty = "Public Property"; // Accessible
$obj->publicMethod(); // Accessible

Protected (protected):

Protected members are accessible within the class and its derived (child) classes.

They are not directly accessible from outside the class hierarchy.

class ParentClass {

    protected $protectedProperty;

    protected function protectedMethod() {

        // Code here

    }

}

class ChildClass extends ParentClass {

    public function accessProtected() {

        $this->protectedProperty = "Protected Property"; // Accessible

        $this->protectedMethod(); // Accessible

    }

}

Private (private):

Private members are accessible only within the class that defines them.

They are not accessible from derived classes or from outside the class.

class MyClass {

    private $privateProperty;

    private function privateMethod() {

        // Code here

    }

}

$obj = new MyClass();
$obj->privateProperty = "Private Property"; // Not accessible (error)
$obj->privateMethod(); // Not accessible (error)

Visibility ensures proper encapsulation and helps maintain the integrity of your classes by preventing unintended access and modifications of class members. It's an important concept in object-oriented programming to ensure that your classes are used as intended and to control the interaction between different parts of your code.