Given this class:
class ValueObject
{
public function __construct(public string $value)
{
}
public function __toString(): string
{
return $this->value . "; this I can control";
}
}
Instances will can be casted to bool, int, and float yet their value is a truthy 1 / true result. It should not be allowed:
$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()`
]);
will print:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 42; this I can control
)
I do see warnings for float and int:
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
yet on first glance the code appears as if working, yet it uses meaningless data.
How can I turn these warnings into an error?
Either for all of these int and float castings, yet better: only for this very class instances.
I can hook into the ::__toString() magic methods, yet there are no equivalents for like ::__toFloat() or ::__toInt().
I am on php 8.0.30.
I realized that this answer would work for me:
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");
Yet I rather only have certain warnings be converted to an Error, not all due to legacy codebase and keeping the impact as low as possible.
Hence, want to throw the error only for specific instances.