Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

__set

Writing a property that is missing or inaccessible from the caller can invoke public `__set` with its name and assigned value.

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

Syntax

public function __set(string $name, mixed $value): void

Writing a property that is missing or inaccessible from the caller can invoke public __set with its name and assigned value. The handler can validate and store that value in existing private storage. Normal assignment to an accessible declared field bypasses the handler. The expression’s result is the assigned value regardless of the handler’s void return.

class Measures {
    public int $revision = 0;
    private array $v = [];
    public function __set(string $name, mixed $value): void {
        if (!is_int($value)) { throw new InvalidArgumentException("integer only"); }
        $this->v[$name] = $value;
    }
    public function values(): array { return $this->v; }
}
$m = new Measures(); $m->revision = 1;
$result = ($m->width = 4);
try { $m->height = "bad"; } catch (InvalidArgumentException $e) { echo $e->getMessage(), PHP_EOL; }
echo json_encode([$result, $m->revision, $m->values()]);
integer only
[4,1,{"width":4}]

Examples

<?php
class Measures {
    public int $revision = 0;
    private array $v = [];
    public function __set(string $name, mixed $value): void {
        if (!is_int($value)) { throw new InvalidArgumentException("integer only"); }
        $this->v[$name] = $value;
    }
    public function values(): array { return $this->v; }
}
$m = new Measures(); $m->revision = 1;
$result = ($m->width = 4);
try { $m->height = "bad"; } catch (InvalidArgumentException $e) { echo $e->getMessage(), PHP_EOL; }
echo json_encode([$result, $m->revision, $m->values()]);

Result

integer only
[4,1,{"width":4}]

Sources