[Tutor] Dynamic creation of class instances...
Erik Price
erikprice@mac.com
Wed, 22 May 2002 23:26:53 -0400
On Wednesday, May 22, 2002, at 03:03 PM, Danny Yoo wrote:
> People with PHP experience appear to take this approach, if:
>
>
> http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html?page=2
> http://www.phpbuilder.com/columns/robert20000928.php3
>
> is a indication of what an experienced PHP programmer can do with
> "variable variables". Yikes. So that may be one source of the
> question.
I did take advantage of variable variables (PHP's equivalent of
exec()ing strings of code) for a bit -- the nature of HTTP sort of
requires it for generating unique form field names:
$data = "";
for ($i = 0; $i < count($items); $i++) {
$data .= "<input type='hidden'
name='uniquefield" . $i
. "' value='" . $items[$i] . "' />\n";
}
Now assuming $items = array('apple', 'orange', 'banana'), $data is equal
to
<input type='hidden' name='uniquefield0' value='apple' />
<input type='hidden' name='uniquefield1' value='orange' />
<input type='hidden' name='uniquefield2' value='banana' />
HTTP doesn't have any means of representing an array per se, so you need
to create unique strings to represent each element when you have no idea
how many elements there may be in the array.
I also use exec quite often in JavaScript. I do it so that I can modify
an object's name based on the argument passed to a function, for
instance:
function chooseInput(inputName)
{
chosenObject = eval('document.formname.' + inputName + '.value');
if (chosenObject == '')
document.write('There is no value in the form field called '
+ inputName + '!');
else
document.write('The value of the form field called '
+ inputName + ' is ' + chosenObject);
}
The above function is stupid and doesn't even return a value, it's just
a subroutine, but it shows how a single function can be used in multiple
parts of a JavaScript/HTML document affecting different form names or
document objects based on the argument to the function.
Note that there is nothing unsafe about the use of exec() or var vars in
either the PHP example or the JavaScript example above, since no user
input is ever evaluated (the argument to the JavaScript function would
be coded into the page by the programmer). And yet each is really
needed to perform its task.
Erik
PS: I stopped using variable variables in PHP when I gave up on hidden
form fields for maintaining state, sessions are just way too easy and
can store objects very well.