PHP4 static properties - PEAR vs my solution
| From: | Hodicska Gergely | Date: | Fri, 06 Oct 2006 12:20:09 +0000 |
| Subject: | PHP4 static properties - PEAR vs my solution | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-44409@lists.php.net to get a copy of this message | ||
Hi!
I had a little discussion on a forum topic about static class method and properties. Somebody there pointed to the PEAR::getStaticProperty() solution to emulate static properties in PHP4. I was not familiar with it but its approach seems a little strange for me. It is not really more than storing static properties in a global array.
I tried to make something better and come out with this solutions, which I think is much more closer to the philosophy of a static property and maybe is more elegant (of course this is subjective :)).
I'm curious about your opinion.
Regards,
Felhő
-------------------------------------------------------------------------
<?php
class base
{
function &staticProperty($name, $value = null)
{
static $properties = array();
if (func_num_args() == 2) {
$properties[$name] = $value;
return $properties[$name];
} else {
if (array_key_exists($name, $properties)) {
return $properties[$name];
} else {
$php4_4suck = null;
return $php4_4suck;
}
}
}
}
class foo extends base
{
}
class bar extends base
{
}
foo::staticProperty('foo', 'foo');
var_dump(bar::staticProperty('foo')); // NULL
bar::staticProperty('foo', 'bar');
var_dump(bar::staticProperty('foo')); // "bar"
$foo = new foo();
var_dump($foo->staticProperty('foo')); // "foo"
$bar = new bar();
var_dump($bar->staticProperty('foo')); // "bar"
$fooStaticProp =& foo::staticProperty('foo');
$fooStaticProp = 'fooChanged';
var_dump($foo->staticProperty('foo')); // "fooChanged"
?>