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.

1

2

3

4

5

newfoo([

'on afterSave'=>function($event){

// this will be triggered by the afterSave method in BaseActiveRecord

},

])

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.

PHP

1

2

3

4

5

6

newfoo([

'as Bar'=>'qualified/namespace/to/bar',

'as fooBar'=>newqualified/namespace/to/fooBar([

'property'=>'value'

])

])

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

/**

* Sets the value of a component property.

* This method will check in the following order and act accordingly:

*

* - a property defined by a setter: set the property value

* - an event in the format of "on xyz": attach the handler to the event "xyz"

* - a behavior in the format of "as xyz": attach the behavior named as "xyz"

* - a property of a behavior: set the behavior property value

*

* Do not call this method directly as it is a PHP magic method that

* will be implicitly called when executing `$component->property = $value;`.