magic method's __set().

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
is it the __set() purpose to be called if a property exists in the
object but is out of the scope.
or is it only to be used for 'undefined instance properties'.


class Magic_Set
    public $fornavn = '';
    private $efternavn = '';

    public function __set($varName, $value)
        if (property_exists($this, $varName)) {
            echo 'edit ['.$varName.'='.$this->$varName.']
            to ['.$varName.'='.$value.']';
        else {
            echo 'defining ['.$varName.'='.$value.']';
        $this->$varName = $value;

$test = new Magic_Set();

$test->fornavn = 'mads';
$test->efternavn = 'jensen';
$test->mellemnavn = 'lee';

Re: magic method's __set().

Quoted text here. Click to load it


The __set() magic function is called whenever an undefined class
variable is set

class Foo
  public function __set($sProp, $Val)
    if(in_array($sProp, $this->arrProps)){
      echo "Found Class Property '$sProp'<br>";
      echo "Invalid Prop '$sProp'<br>";
      $this-> = $Val; // define it ;)

  protected $arrProps = array("FirstName", "LastName");

  public $Test = "";

$Foo = new Foo();
$Foo->FirstName = "Hugo";

// __set gets called
$Foo->tName = "Hugo";

// tName is defined
echo $Foo->tName;

// no __set gets called
$Foo->tName = "Hugo3";

echo $Foo->tName;

// no __set gets called because of object member
$Foo->Test= "no set calles";

hope this helps

Site Timeline