Sobes.tech
Junior

What are visibility modifiers in PHP?

sobes.tech AI

Answer from AI

Visibility modifiers (public, protected, private) define the access level to class properties and methods.

  • public - accessible from anywhere (inside the class, inherited classes, outside).
  • protected - accessible within the class and in classes that inherit from it.
  • private - accessible only within the class where it is declared.

Example:

<?php

class MyClass {
    public $publicProperty = 'public';
    protected $protectedProperty = 'protected';
    private $privateProperty = 'private';

    public function publicMethod() {
        echo "Public method access: " . $this->publicProperty . ", " . $this->protectedProperty . ", " . $this->privateProperty . "\n";
    }

    protected function protectedMethod() {
        echo "Protected method access: " . $this->publicProperty . ", " . $this->protectedProperty . ", " . $this->privateProperty . "\n";
    }

    private function privateMethod() {
        echo "Private method access: " . $this->publicProperty . ", " . $this->protectedProperty . ", " . $this->privateProperty . "\n";
    }
}

class MyChildClass extends MyClass {
    public function testAccess() {
        echo "Child class access: " . $this->publicProperty . ", " . $this->protectedProperty . "\n"; // Access to public and protected
        // echo $this->privateProperty; // Error, private not accessible
        $this->publicMethod();
        $this->protectedMethod();
        // $this->privateMethod(); // Error, private not accessible
    }
}

$obj = new MyClass();
echo $obj->publicProperty . "\n"; // Accessible
// echo $obj->protectedProperty; // Error, protected not accessible from outside
// echo $obj->privateProperty; // Error, private not accessible from outside
$obj->publicMethod();
// $obj->protectedMethod(); // Error, protected not accessible from outside
// $obj->privateMethod(); // Error, private not accessible from outside

$childObj = new MyChildClass();
$childObj->testAccess();
What are visibility modifiers in PHP? — PHP - sobes.tech