Page 1 of 1

Variable on the fly in Class

Posted: Mon Mar 23, 2009 10:16 am
by mikeynl
Hi, I have a class Customer with a bunch of protected variables like $_name, $_address, etc. If I wanna read the variables I could write a function for every protected variable like

Code: Select all

 
public function getAddress() {return $this->_address}
 
etc. Since the number of protected variables is getting rather large in my program, and I don't want to make them public, I would like to make one function that would show return the variable ... something like:

Code: Select all

 
class Customer {
protected $_name;
protected $_address;
 
public function getVar($str) {
// some code to return variable with name $this->_$str
}
 
}
 
$customer = new Customer("John Doe, Main Street 1, ...);
echo $customer->getVar("address");
 
What code would I need in the getVar function to return the value of $_address?

Re: Variable on the fly in Class

Posted: Mon Mar 23, 2009 10:24 am
by php_east
i use this one i made a lot ...

Code: Select all

    function get_var($varname)
    {
    return ($this->{$varname});
    }
 
    function set_var($varname,$var)
    {
    $this->{$varname} = $var;
    }
 

Re: Variable on the fly in Class

Posted: Mon Mar 23, 2009 1:30 pm
by mikeynl
Thanks, I had figured something like this, but I want to make it look just a little bit nicer. The protected variables all start with an underscore like $_address, and I find it ugly to call them like ..getVar("_address"). Is there any way to add the underscore inside the class? I have tried:

Code: Select all

 
function get_var($varname)
{
   return ($this->_{$varname});
}
#  
 
but that won't work...

Re: Variable on the fly in Class

Posted: Mon Mar 23, 2009 1:33 pm
by mikeynl
Ah, a simple

Code: Select all

 
function get_var($varname)
{
   $varname .= "_" . $varname;
   return $this->{$varname};
}
 
does the trick :)