Example:
error_reporting(E_ALL | E_STRICT);
class Test {}
$obj = new Test();
$obj->undeclared = "oops"; // I want an error here !! :(
echo $obj->algo; // oops
I tested it on PHP 5.2.11 and 5.3.0.
I don't want dynamic properties in my objects.
Is possible to force PHP to raise an ERROR in that situation ?
Use __set() ?
<?php
class Test {
public $bar;
public function __set($name, $value) {
throw new Exception('Cant set!');
}
}
$obj = new Test;
$obj->bar = 'foo';
$obj->foo = 'evil';
?>
A bit more diligence with your error message and you can help your own coding. Having the following as your base class setup will:
public function __set($name,$value) {
switch ($name) {
default:
// we don't allow any magic properties set or overwriting our properties
try {
$error = "Assignment of {$name} in " . static::class . ' not allowed because it is a magic variable or read-only property.';
throw new \RuntimeException($error);
} catch ( \RuntimeException $e ) {
echo 'Caught exception: ' . $e->getMessage() . PHP_EOL;
}
}
}
public function __get($name)
{
switch ($name) {
default:
// we don't allow any magic properties
try {
$error = "var {$name} is not a property of " . static::class . '.';
throw new \RuntimeException($error);
} catch ( \RuntimeException $e ) {
echo 'Caught exception: ' . $e->getMessage() . PHP_EOL;
}
}
return null;
}
public function __isset($name)
{
switch ($name) {
default:
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With