'How many times will this magic method ( __set ) be performed ? Why?

class abc{
    function __construct(){
        $this->abc = 123;
    }
    
    function index(){
        $this->abc = 2222;
    }
    
    //How many times will this magic method  be performed ?
    function __set($name,$value){
        $this->$name = $value;
        echo $value;
    }
}

class abc2 extends abc{
    function __construct(){
        parent::__construct();
        parent::index();
        $this->abc = 3333;
    }
}

$abc2 = new abc2();
echo $abc2->index();

Shouldn't it be performed three times?

php


Solution 1:[1]

it should be performed only 1 time, because magic method __set is executed only if variable is not defined, during first call - variable gets defined and thus no more calls should happen

though, if you comment $this->$name = $value; part - you will see that __set is executed 4 times:

  1. abc constructor
  2. abc index via abc2 construct
  3. abc2 construct
  4. abc2 index (which is actually abc index)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iłya Bursov