CKTIS / PHP
__get
Ob branju manjkajoče ali nedostopne lastnosti lahko javna metoda `__get` prejme njeno ime.
Različica: PHP 8.4; repository runtime, production runtime not attested
Sintaksa
public function __get(string $name): mixedOb branju manjkajoče ali nedostopne lastnosti lahko javna metoda __get prejme njeno ime. Vrnjena vrednost, na primer iz zasebnega polja, je rezultat branja. Običajna dostopna lastnost se bere neposredno. Za neznano ime je vrnitev null odločitev primera.
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"]]
Primeri
<?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]);
Rezultat
["visible",0,null,["score","absent"]]