Sobes.tech
Junior

Was sind Sichtbarkeitsmodifikatoren in PHP?

sobes.tech KI

Antwort von AI

Sichtbarkeitsmodifikatoren (public, protected, private) bestimmen das Zugriffslevel auf Eigenschaften und Methoden einer Klasse.

  • public - zugänglich von überall (innerhalb der Klasse, in vererbten Klassen, von außen).
  • protected - zugänglich innerhalb der Klasse und in den von ihr ererbten Klassen.
  • private - nur innerhalb der Klasse, in der sie deklariert sind.

Beispiel:

<?php

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

    public function publicMethod() {
        echo "Öffentliche Methode: " . $this->publicProperty . ", " . $this->protectedProperty . ", " . $this->privateProperty . "\n";
    }

    protected function protectedMethod() {
        echo "Geschützte Methode: " . $this->publicProperty . ", " . $this->protectedProperty . ", " . $this->privateProperty . "\n";
    }

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

class MyChildClass extends MyClass {
    public function testAccess() {
        echo "Zugriff in Kindklasse: " . $this->publicProperty . ", " . $this->protectedProperty . "\n"; // Zugriff auf public und protected
        // echo $this->privateProperty; // Fehler, private nicht zugänglich
        $this->publicMethod();
        $this->protectedMethod();
        // $this->privateMethod(); // Fehler, private nicht zugänglich
    }
}

$obj = new MyClass();
echo $obj->publicProperty . "\n"; // Verfügbar
// echo $obj->protectedProperty; // Fehler, protected nicht zugänglich von außen
// echo $obj->privateProperty; // Fehler, private nicht zugänglich von außen
$obj->publicMethod();
// $obj->protectedMethod(); // Fehler, protected nicht zugänglich von außen
// $obj->privateMethod(); // Fehler, private nicht zugänglich von außen

$childObj = new MyChildClass();
$childObj->testAccess();