Perhaps you have a class and you absolutely don’t want anyone tacking new properties onto it once it’s been instantiated. To do so, you can use PHP’s overloading to catch the setting of a variable and raise an error accordingly. Here is the default behavior where an object can have new properties defined on the fly:

class Object
{
}

$object      = new Object();
$object->foo = 'bar'; // No error

print_r($object); // public $foo => string(3) "bar"

And here’s how we can define a __set() method to help catch this behavior:

class Object
{
	public $test;

	public function __set($variable, $value)
	{
		throw new Exception('Setting "' . $variable . '" is forbidden!');
	}
}

$object       = new Object();
$object->test = 'ing'; // All good!
$object->foo  = 'bar'; // Exception will be thrown!

Pretty simple stuff. Basically any variable that isn’t already defined in the class and is public will throw an exception. But what if you wanted to make your variables private? That will take a bit of extra coding but still isn’t all that difficult:

class Object
{
	private $test;

	public function __set($variable, $value)
	{
		if (!property_exists($this, $variable))
		{
			throw new Exception('Setting "' . $variable . '" is forbidden!');
		}

		$this->$variable = $value;
	}
}

$object       = new Object();
$object->test = 'ing'; // All good!
$object->foo  = 'bar'; // Exception will be thrown!

Please note that the use of the property_exists() method is only available in PHP 5.1.0 and above.





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: