CKTIS / PHP
__get
Reading a missing property or one inaccessible in the current scope can invoke the public `__get` with the property name.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __get(string $name): mixedReading a missing property or one inaccessible in the current scope can invoke the public __get with the property name. The handler supplies the read result and can use private backing storage. A read of an accessible ordinary public property bypasses it. Returning null for an unknown name is a decision made by this handler.
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"]]
Examples
<?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]);
Result
["visible",0,null,["score","absent"]]