Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

__set

Scrivere una proprietà assente o inaccessibile può chiamare il metodo pubblico `__set` con nome e valore assegnato.

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

Sintassi

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

Scrivere una proprietà assente o inaccessibile può chiamare il metodo pubblico __set con nome e valore assegnato. Il metodo può convalidare il valore e conservarlo in un array privato. Un normale campo accessibile si scrive direttamente. L’assegnazione vale l’operando destro anche se il metodo dichiara 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}]

Esempi

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

Risultato

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

Fonti