Jump to content

magic methods


raindropz12

Recommended Posts

Well, usually you can only access object properties if they are defined:

<?php

class Person
{
  public $name;
  public $age;
  public $title = 'Sir';
}

$p = new Person();
echo $p->title;
//Sir

$p->name = 'Atticus';
echo $p->name;
//Atticus

$p->age = 48;
echo $p->age;
//48

?>

 

The magic method __set() (usually combined with __get() ) allows you to define and access object properties dynamically.

 

<?php

class Person
{

  public $data = array();

  public function __set($name, $value)
  {
    $this->data[$name] = $value;
  }

  public function __get($name)
  {
    if(isset($this->data[$name]))
    {
      return $this->data[$name];
    }
    else
    {
      echo 'NOT SET';
    }
  }

}

$z = new Person();

echo $z->title;
//NOT SET

$z->name = 'Atticus';
echo $z->name;
//Atticus

$z->age = 48;
echo $z->age;
//48

?>

Link to comment
https://forums.phpfreaks.com/topic/233316-magic-methods/#findComment-1200423
Share on other sites

Well, usually you can only access object properties if they are defined:

<?php

class Person
{
  public $name;
  public $age;
  public $title = 'Sir';
}

$p = new Person();
echo $p->title;
//Sir

$p->name = 'Atticus';
echo $p->name;
//Atticus

$p->age = 48;
echo $p->age;
//48

?>

 

The magic method __set() (usually combined with __get() ) allows you to define and access object properties dynamically.

 

<?php

class Person
{

  public $data = array();

  public function __set($name, $value)
  {
    $this->data[$name] = $value;
  }

  public function __get($name)
  {
    if(isset($this->data[$name]))
    {
      return $this->data[$name];
    }
    else
    {
      echo 'NOT SET';
    }
  }

}

$z = new Person();

echo $z->title;
//NOT SET

$z->name = 'Atticus';
echo $z->name;
//Atticus

$z->age = 48;
echo $z->age;
//48

?>

did you mean __set_state is the same as __set?

 

Link to comment
https://forums.phpfreaks.com/topic/233316-magic-methods/#findComment-1201984
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.