Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

__set

Escrever numa propriedade ausente ou inacessível pode chamar o método público `__set` com o nome e o valor atribuído.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

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

Escrever numa propriedade ausente ou inacessível pode chamar o método público __set com o nome e o valor atribuído. Pode validar e guardar o valor num array privado. Um campo comum acessível é alterado diretamente. A atribuição produz o operando direito mesmo que o método declare 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}]

Exemplos

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

Resultado

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

Fontes