Skip to content
PHP Logo

What are the different visibility levels for variables in PHP classes and how does it affect access from other classes?

In PHP classes, there are three visibility levels for variables: public, protected, and private. Public variables can be accessed from outside the class, protected variables can be accessed from within the class and its subclasses, and private variables can only be accessed from within the class itself. This affects access from other classes as they can only access public variables directly, while protected and private variables require getter and setter methods to access or modify their values.

php
class MyClass {
    public $publicVar;
    protected $protectedVar;
    private $privateVar;

    public function getProtectedVar() {
        return $this->protectedVar;
    }

    public function setPrivateVar($value) {
        $this->privateVar = $value;
    }
}

$obj = new MyClass();
$obj->publicVar = "Public Variable"; // Accessible
$obj->protectedVar = "Protected Variable"; // Error: Cannot access protected property
$obj->privateVar = "Private Variable"; // Error: Cannot access private property
echo $obj->getProtectedVar(); // Accessing protected variable using getter method
$obj->setPrivateVar("New Private Value"); // Modifying private variable using setter method