Re: generically accessing member variables problem

From: Date: Wed, 06 Nov 2002 17:45:34 +0000
Subject: Re: generically accessing member variables problem
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-123030@lists.php.net to get a copy of this message
Tom Rogers <trogers@kwikin.com> wrote... : > > Amazing what you learn on this list :) > This works: > > class Example > { > var $array1 = array(); > var $array2 = array(); > var $array3 = array(); > > function add2array($array_name,$val){ > $this->{"$array_name"}[] = $val; > } > > } > $t = new Example(); > $t->add2array('array1',25); > $t->add2array('array2',26); > $t->add2array('array3',"Hello"); > echo '<pre>'; > print_r($t); > echo '</pre>'; > Yet, this is not a such elegant way doing it. It can be helpful in a lot of cases, but most often, element key is enough. Try rethinking your logic: class Example { var $array = array(); function add2array($element_name, $val){ $this->$array[$element_name] = $val; } } $t = new Example(); $t->add2array('array1',25); $t->add2array('array2',26); $t->add2array('array3',"Hello"); echo '<pre>'; print_r($t); echo '</pre>'; Cleaner and more scalable, no? -- Maxim Maletsky maxim@php.net

« previous php.general (#123030) next »