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.
dynamically set variable?
Moderator: General Moderators
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