Code: Select all
class ValueObject
{
public function __construct(public string $value)
{
}
public function __toString(): string
{
return $this->value . "; this I can control";
}
}
Code: Select all
$object = new ValueObject('42');
print_r([
(int) $object, // should throw
(float) $object, // should throw
(bool) $object, // should throw, but only for this class instances, yet ok if not possible
(string) $object, // I can make it throwable via `::__toString()`
]);
< /code>
wird gedruckt: < /p>
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 42; this I can control
)
< /code>
Ich sehe Warnungen für Float und int: < /p>
PHP Warning: Object of class Application\ValueObject could not be converted to int
PHP Warning: Object of class Application\ValueObject could not be converted to float
< /code>
Auf dem ersten Blick erscheint der Code so, als würde er funktionieren, aber es verwendet sinnlose Daten. < /p>
Wie kann ich diese Warnungen in einen Fehler verwandeln? < /p>
Entweder für alle diese int- und float -Castings, doch besser: Nur für diese Klasseninstanzen. )
Ich bin auf PHP 8.0.30.function exception_error_handler(int $errno, string $errstr, string $errfile = null, int $errline) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler(__NAMESPACE__ . "\\exception_error_handler");
< /code>
Ich habe jedoch lieber nur bestimmte Warnungen auf einen Fehler umgewandelt, nicht alle aufgrund der Legacy -Codebasis und den Auswirkungen so niedrig wie möglich. < /p>
Daher möchten Sie den Fehler nur für bestimmte Instanzen werfen.