Validation
Validation via the validate Method
validate MethodThe Serialize class provides a validate method that is automatically called when an object is created using the from method. You can implement custom data validation logic within this method.
Here's an example:
use Astral\Serialize\Serialize;
class TestConstructValidationFromSerialize extends Serialize
{
public string $type_string;
/**
* Data validation method
* Automatically called after object creation via the from method
*/
public function validate(): void
{
// Validate the value of the type_string property
if ($this->type_string !== '123') {
throw new Exception('type_string must be equal to 123');
}
// You can also modify property values
$this->type_string = '234';
}
}Validation in __construct
__constructWhen creating objects directly using the __construct method, you can implement parameter validation logic in the constructor. However, note that this approach can only access properties defined in the constructor and cannot access other properties.
最后更新于