Magic Methods And Events/behaviors

Looking at the source of Component.php i found this code in the magic __set():




	public function __set($name, $value)

	{

		$setter = 'set' . $name;

		if (method_exists($this, $setter)) {

			// set property

			$this->$setter($value);

			return;

		} elseif (strncmp($name, 'on ', 3) === 0) {

			// on event: attach event handler

			$this->on(trim(substr($name, 3)), $value);

			return;

		} elseif (strncmp($name, 'as ', 3) === 0) {

			// as behavior: attach behavior

			$name = trim(substr($name, 3));

			$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));

			return;

That basically means because of the extra space we have to use it like this:


$component->{'on something'} = function() ...

I wonder what was the backround of this decision. Why isn’t it simply $component->onSomething = …?

Actually (I think) it will be like this:




$component->on('something', function() { ... });



the ‘on something’ way is for when you want to do something like:




$this->widget('somewidget', array(

    'on something' => function() {...},

    'on somethingElse' => function() {...},

));



etc.

I am not 100% this is correct tho :)

Fragoulas is correct. See Qiang’s post here.

I didn’t check the code yet, but it appears that it is handed over to __set to discover and attach the handler.

I see now. Thanks!

Relying on a single tiny space character between ‘on’ and ‘someting’ seems to me a potential source of suicide among Yii2 developers (in particular after 2 am)

B)