views:

399

answers:

1

Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an (object) $myarray or whatever it is, but that will create a new stdClass and doesn't help me much. Are there any easy one or two line methods to make each $key => $value pair in my array into a $key = $value variable for my class? I don't find it very logical to use a foreach loop for this, I'd be better off just converting it to a stdClass and storing that in a variable, wouldn't I?

class MyClass {
    var $myvar; // I want variables like this, so they can be references as $this->myvar
    function __construct($myarray) {
        // a function to put my array into variables
    }
}
+6  A: 

This simple code should work:

<?php

  class MyClass {
    public function __construct(Array $properties=array()){
      foreach($properties as $key => $value){
        $this->{$key} = $value;
      }
    }
  }

?>

Example usage

$foo = new MyClass(array("hello" => "world"));
$foo->hello // => "world"

Alternatively, this might be a better approach

<?php

  class MyClass {

    private $_data;

    public function __construct(Array $properties=array()){
      $this->_data = $properties;
    }

    // magic methods!
    public function __set($property, $value){
      return $this->_data[$property] = $value;
    }

    public function __get($property){
      return array_key_exists($property, $this->_data)
        ? $this->_data[$property]
        : null
      ;
    }
  }

?>

Usage is the same

// init
$foo = new MyClass(array("hello" => "world"));
$foo->hello;          // => "world"

// set: this calls __set()
$foo->invader = "zim";

// get: this calls __get()
$foo->invader;       // => "zim"

// attempt to get a data[key] that isn't set
$foo->invalid;       // => null
macek
Don't think you need the { } in the $this->{$key} = $value; statement
AntonioCS
@AntonioCS, it's not necessary but it definitely emphasizes the access of a variable-named property. It also demonstrates that `{ }` can be used when the variable property becomes more complex; e.g., `$this->{$this->foo('bar')}->do_something();`
macek
@Macek: Good point :)
AntonioCS