Re: variable variables with classes

From: Date: Mon, 11 Sep 2000 01:25:23 +0000
Subject: Re: variable variables with classes
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-16102@lists.php.net to get a copy of this message
Cynic writes: > What's the correct syntax for variable variables used in > classes? > I wanted to use a generic handler for class variables: > > function setProperty( $var , $val ) > { > $this->$$var = $val ; > } > > but this doesn't do anything except a warning. You're very, very close. :) Since the proper way to reference a property is '$this->property', one more level of 'indirection' is achieved by adding a single dollar sign after the '->', not two: <?php error_reporting(E_ALL); class foo { function setprop($prop, $val) { $this->$prop = $val; } function printprop($prop) { if (!isset($this->$prop)) return false; echo $this->$prop . "\n"; } } $foo = new foo(); $foo->setprop('bar', 'This is bar'); $foo->setprop('quux', 'This is quux'); $foo->printprop('bar'); $foo->printprop('quux'); ?> Hope this helps, Torben -- +----------------------------------------------------------------+ |Torben Wilson <torben@php.net> Netmill iTech| |http://www.coastnet.com/~torben http://www.netmill.fi| |Ph: 1 250 383-9735 torben@netmill.fi| +----------------------------------------------------------------+

« previous php.general (#16102) next »