Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / PHP

__get

Odczyt brakującej lub niedostępnej w danym zakresie właściwości może wywołać publiczną metodę `__get` z jej nazwą.

Wersja: PHP 8.4; repository runtime, production runtime not attested

Składnia

public function __get(string $name): mixed

Odczyt brakującej lub niedostępnej w danym zakresie właściwości może wywołać publiczną metodę __get z jej nazwą. Metoda zwraca wartość odczytu, np. z prywatnej tablicy. Zwykłe dostępne pole ją omija. Dla nieznanej nazwy to implementacja przykładu wybiera null.

class Survey {
    public string $title = "visible";
    private array $data = ["score" => 0];
    public array $reads = [];
    public function __get(string $name): mixed {
        $this->reads[] = $name;
        return $this->data[$name] ?? null;
    }
}
$s = new Survey();
echo json_encode([$s->title, $s->score, $s->absent, $s->reads]);
["visible",0,null,["score","absent"]]

Przykłady

<?php
class Survey {
    public string $title = "visible";
    private array $data = ["score" => 0];
    public array $reads = [];
    public function __get(string $name): mixed {
        $this->reads[] = $name;
        return $this->data[$name] ?? null;
    }
}
$s = new Survey();
echo json_encode([$s->title, $s->score, $s->absent, $s->reads]);

Wynik

["visible",0,null,["score","absent"]]

Źródła