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:
And here’s how we can define a
__set() method to help catch this behavior:
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:
Please note that the use of the
property_exists() method is only available in PHP 5.1.0 and above.