Voting

: six plus two?
(Example: nine)

The Note You're Voting On

http://sc.tri-bit.com/ StoneCypher
20 years ago
to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There's a much easier solution to getting a class' name for working with a factory function. Let's assume you're doing something like this:

<?php

function FactoryFunction($whatever, $instancedata) {

switch (
$whatever) {
case
'stuff' : return new Stuff($instancedata);
case
'otherstuff' : return new Otherstuff($instancedata);
}

}

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

<?php

function FactoryFunction($whatever, $instancedata) {

switch (
$whatever) {

case
'stuff' : return array('typeis'=>'stuff', 'instance'=>new Stuff($instancedata));
case
'otherstuff' : return array('typeis'=>'otherstuff', 'instance'=>new Otherstuff($instancedata));

}

}

?>

Nice 'n simple. It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior. If you move to PHP5, the static keyword solves your problem cleanly.

<< Back to user notes page

To Top