Created
March 7, 2023 23:26
-
-
Save IgorDePaula/afb9eec6e271d6968d20a2ecae8def0e to your computer and use it in GitHub Desktop.
Atributo com php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
#[Attribute] | |
class Validacao { | |
public function __construct( | |
public string $regra, | |
public int $valor | |
){} | |
public function validate(int $value) | |
{ | |
if($value > $this->valor){ | |
throw new Exception('Limite de velocidade excedida'); | |
} | |
} | |
} | |
class Carro { | |
#[Validacao('max', 110)] | |
public int $velocidade; | |
} | |
$carro = new Carro(); | |
$carro->velocidade = 139; | |
$informacoesClasseCarro = new reflectionClass($carro); | |
foreach ($informacoesClasseCarro->getProperties() as $propriedade) { | |
$value = $propriedade->getValue($carro); | |
$atributosDaPropriedade = $propriedade->getAttributes(Validacao::class); | |
foreach ($atributosDaPropriedade as $atributo) { | |
$atributoInstance = $atributo->newInstance(); | |
$atributoInstance->validate($value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment