Software is like sex... It's better when it's free.

Blog - Access to a PHP variable without knowing its name

Access to a PHP variable without knowing its name

If you want to push the generic with PHP and you want to access PHP variables without knowing their names, know that it can fairly easily without using eval() function or other code unreadable.

Indeed, the flexibility of PHP allows you to "generate" variable names using the characters {}, a small example, suppose a class representing a model (here a news), deliberately simplified.

<?php
class News
{
  private $news_title;
  private $news_description;

  public function __construct($_news_title,$news_description)
  {
    $this->news_title = $_news_title;
    $this->news_description = $news_description;
  }

  public function __get($name)
  {
    return $this->{$name};
  }
}
?>

Thanks to generic getter __get (), we can access class variables without knowing their name. Imagine, in another file a variable contains the string describing the class variable, we can recover the value from an abstract way like this :

<?php
include("News.class.php");
$news = new News("title","content");
$generic = "news_title";
var_dump($news->__get($generic));
// Display "String(7) content";
?>
Tags:  abstractgenericphp.
Posted the Tuesday 02 june 2009 18:01:21