Sobes.tech
Junior

What visibility modifiers exist in PHP?

sobes.tech AI

Answer from AI

In PHP, there are three visibility modifiers for properties, methods, and constants:

  • public: The element is accessible from anywhere - inside the class, in inheriting classes, and outside the class instance.
  • protected: The element is accessible from inside the class and all inheriting classes. It is not accessible outside the class instance.
  • private: The element is accessible only from within the class where it is declared. It is not accessible from inheriting classes or outside the class instance.

Example of usage:

<?php
class MyClass {
    public $publicProperty = 'Public';
    protected $protectedProperty = 'Protected';
    private $privateProperty = 'Private';

    public function publicMethod() {
        echo $this->publicProperty . "\n";
        echo $this->protectedProperty . "\n";
        echo $this->privateProperty . "\n"; // Access inside the class
    }

    protected function protectedMethod() {
        echo $this->publicProperty . "\n";
        echo $this->protectedProperty . "\n";
        // echo $this->privateProperty . "\n"; // Error: private is not accessible in a protected method outside the same class
    }

    private function privateMethod() {
        echo $this->publicProperty . "\n";
        echo $this->protectedProperty . "\n";
        echo $this->privateProperty . "\n"; // Access inside the class
    }
}

class ChildClass extends MyClass {
    public function testAccess() {
        echo $this->publicProperty . "\n"; // Access: public is accessible in inheriting class
        echo $this->protectedProperty . "\n"; // Access: protected is accessible in inheriting class
        // echo $this->privateProperty . "\n"; // Error: private is not accessible in inheriting class

        $this->publicMethod();    // Access: public method is accessible
        $this->protectedMethod(); // Access: protected method is accessible
        // $this->privateMethod(); // Error: private method is not accessible
    }
}

$obj = new MyClass();
echo $obj->publicProperty . "\n"; // Access: public is accessible outside

// echo $obj->protectedProperty . "\n"; // Error: protected is not accessible outside
// echo $obj->privateProperty . "\n";   // Error: private is not accessible outside

$obj->publicMethod(); // Access: public method is accessible outside
// $obj->protectedMethod(); // Error: protected method is not accessible outside
// $obj->privateMethod();  // Error: private method is not accessible outside

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