Page 1 of 1

dynamically set variable?

Posted: Fri Sep 17, 2004 11:19 am
by jessevitrone
This is a php 4 question, I know php 5 is introducing reflection, but my web host isn't supporting 5 yet, so I'd like to stick to 4 for now.

Is there a way to set a variable if I have the variable name as a string? I'd like to make a utility for my constructor to use that would take an associative array like this:

array("id" => 1, "name" => "Joe");

I'd like to have the constructor loop through the array, and if there is a member variable with the same name as the key, set the value. (In the array above, my object would get $this->id and $this->name set).

Is there any way to do this?

Thanks.

Posted: Fri Sep 17, 2004 12:29 pm
by feyd
read the topics in this search: [devnet]metaprogramming[/devnet]

Posted: Fri Sep 17, 2004 12:33 pm
by markl999
Something like:

Code: Select all

<?php

class Foo {
  var $id;
  var $name;
  var $dummy;
  function Foo($arr){
    //get the existing class variables
    $classVars = array_keys(get_class_vars(get_class($this)));
    foreach($arr as $key=>$val){
      if(in_array($key, $classVars)){
        echo $key.' found<br />';
        $this->$key = $val;
      } else {
        echo $key.' not found<br />';
      }
    }
  }
}

$array = array(
  'id' => 1,
  'name' => 'Joe',
  'invalid' => 'blah' //this doesn't exist as a class var
);
$fooObj =& new Foo($array);
//some tests below
echo $fooObj->id.'<br />';
echo $fooObj->name.'<br />';
echo $fooObj->dummy.'<br />';
?>
?

Posted: Fri Sep 17, 2004 12:38 pm
by jessevitrone
Great, that's just what I was looking for. Thanks.