Variable on the fly in Class

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
mikeynl
Forum Newbie
Posts: 7
Joined: Wed Jan 28, 2009 6:58 am

Variable on the fly in Class

Post 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?
User avatar
php_east
Forum Contributor
Posts: 453
Joined: Sun Feb 22, 2009 1:31 pm
Location: Far Far East.

Re: Variable on the fly in Class

Post 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;
    }
 
mikeynl
Forum Newbie
Posts: 7
Joined: Wed Jan 28, 2009 6:58 am

Re: Variable on the fly in Class

Post 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...
mikeynl
Forum Newbie
Posts: 7
Joined: Wed Jan 28, 2009 6:58 am

Re: Variable on the fly in Class

Post by mikeynl »

Ah, a simple

Code: Select all

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