Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.