Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / PHP

__set

Ob pisanju v manjkajočo ali nedostopno lastnost lahko javna metoda `__set` prejme ime in dodeljeno vrednost.

Različica: PHP 8.4; repository runtime, production runtime not attested

Sintaksa

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

Ob pisanju v manjkajočo ali nedostopno lastnost lahko javna metoda __set prejme ime in dodeljeno vrednost. Vrednost lahko preveri in zasebno shrani. Običajna dostopna lastnost se spremeni neposredno. Prirejanje vrne desni operand tudi pri tipu vrnitve void.

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}]

Primeri

<?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()]);

Rezultat

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

Viri