Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using variable variables to assign private variables... 1

Status
Not open for further replies.

Geates

Programmer
Aug 25, 2009
1,566
US
I'm using variable variables to try to assign a value to some (not all) private variables in a class using a public function and an array as input. However, the values don't seem to get assigned to the private vars. The code seems logical but am I missing something? Perhaps I'm going about it the wrong way. Any suggestions?

Code:
class aClass {
    private $_fruitA;
    private $_fruitB;
    private $_fruitC;

    public function set($inputArray)
    {
        foreach ($inputArray as $key=>$val)
        {
            $var = "this->_{$key}";
            $$var = $val;

            //prints nothing
            print "this->_$key: ".$this->_fruit."\n";

            //prints the $val assigned in $inputArray
            print "\$\$var: ".$$var."\n\n";   
        }
    }
}

$fruit = new aClass();
$fruit->set(array('fruitA' => 'apple', 'fruitB' => 'banana'));

-Geates

"I hope I can chill and see the change - stop the bleed inside and feel again. Cut the chain of lies you've been feeding my veins; I've got nothing to say to you!"
-Infected Mushroom

"I do not offer answers, only considerations."
- Geates's Disclaimer
 
not sure of the point of your experiment (why not pass in the keys with the prepended underscore?) but this works fine for me

Code:
 public function set($inputArray){
        foreach ($inputArray as $key=>$val):
        	$this->{'_' . $key} = $val;   
        endforeach;
	var_dump($this);
    }

you can also use the overloading magic methods to achieve the same thing.
 
for me as well. This is also a cleaner approach. Thanks jpadie

-Geates

"I hope I can chill and see the change - stop the bleed inside and feel again. Cut the chain of lies you've been feeding my veins; I've got nothing to say to you!"
-Infected Mushroom

"I do not offer answers, only considerations."
- Geates's Disclaimer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top