Magic Methods Within Yii2 __set

This article is continued from the previous post about the __get method.

The basic __set  method is contained within the Object class and performs a simple check to ensure a property can be set. It looks for a method with the ‘set’ prefix, executes if found, or, if not, checks to see if the property is readonly by looking for a ‘get’ prefix and finally throws an unknown property exception. 

This works well to insure that all objects contain the properties necessary for them to function; however, if you wish to dynamically generate properties, you will have to overwrite this method in order to do so.

The more complicated version is found within the Component class. As you can see, the same set method check as the Object class. However, instead of continuing on like the base class, it performs two more checks. Using a binary string comparison (strncmp) it checks to see if you’re trying to dynamically set an event or attach a behavior. Finally it will attempt to set a property and attached behavior.

By prefixing your property name with ‘on ‘ you can attach an anonymous function to the property name as the name of the event.

By prefixing your property name with ‘as ‘ you can attach a behavior with the property name as the name of the behavior within the class.

 

Again, this works quite well for most situations, but, if you’re attempting to dynamically add properties to a class, this will prevent such an action.

Now, this only covers the base Object and Component class’s __set methods; however, they are the most complicated ones. Please refer to the methods for __set in BaseActiveRecord, DynamicModel, and GenerateController.