Sobes.tech
Junior — Middle

What types of access restrictions to properties and methods in PHP do you know?

sobes.tech AI

Answer from AI

In PHP, there are three main levels of access to class properties and methods:

  • public — access is open everywhere, from any part of the code.
  • protected — access is allowed within the class itself and its descendants.
  • private — access is only allowed within the class itself; even descendants cannot access it.

Example:

class Example {
    public $publicProp = 'public';
    protected $protectedProp = 'protected';
    private $privateProp = 'private';

    public function showProps() {
        echo $this->publicProp . "\n";
        echo $this->protectedProp . "\n";
        echo $this->privateProp . "\n";
    }
}

class ChildExample extends Example {
    public function showProtected() {
        echo $this->protectedProp; // Access is allowed
        // echo $this->privateProp; // Error, private is not accessible
    }
}

$obj = new Example();
$obj->showProps();
// echo $obj->protectedProp; // Error
// echo $obj->privateProp; // Error

These restrictions help encapsulate data and control access to the internal state of objects.

What types of access restrictions to properties and… - sobes.tech