The 'magic method' __set (if declared) is called when writing data to inaccessible properties.
You can use this to your advantage to prevent the creation of undeclared properties:
<?php
class Foo
{
public $bar;
private $baz;
public function __set($name, $value)
{
throw new Exception('Strictly no writes to inaccesible and undeclared properties.');
}
}
$f = new Foo;
$f->bar = 'hello';
$f->qux = 'earth';
Output:
Fatal error: Uncaught Exception: Strictly no writes to inaccesible and undeclared properties. in /var/www/stackoverflow/so-tmp-f2.php:20 Stack trace: #0 /var/www/stackoverflow/so-tmp-f2.php(26): Foo->__set('qux', 'earth') #`1 {main} thrown in /var/www/stackoverflow/so-tmp-f2.php on line 20
As you can see, the above will throw an exception when trying to write to an undeclared property.
If you try to write to another inaccessible property (in a similar scope) like Foo::baz above (which is declared private), calls will be routed through the __set magic method also. Without the __set method this will result in a Fatal Error.
However, a write to Foo::bar (declared public above) will NOT be routed through the __set magic method.
If you want to enforce this type of strict behaviour in many classes you could implement the above as a trait:
trait Upsetter
{
public function __set($name, $value)
{
throw new Exception('Strictly no writes to inaccesible and undeclared properties.');
}
}
class Bob
{
use Upsetter;
}