dynamically set variable?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jessevitrone
Forum Newbie
Posts: 15
Joined: Tue Aug 12, 2003 2:42 pm

dynamically set variable?

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

read the topics in this search: [devnet]metaprogramming[/devnet]
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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 />';
?>
?
jessevitrone
Forum Newbie
Posts: 15
Joined: Tue Aug 12, 2003 2:42 pm

Post by jessevitrone »

Great, that's just what I was looking for. Thanks.
Post Reply