Re: Static variable in a class method
| From: | Nathan Rixham | Date: | Thu, 14 Feb 2008 18:42:47 +0000 |
| Subject: | Re: Static variable in a class method | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-269305@lists.php.net to get a copy of this message | ||
Nathan Nobbe wrote:
On Thu, Feb 14, 2008 at 12:10 PM, Eric Butera <eric.butera@gmail.com> wrote:static variables save your scripts repeating themselves.. class used_all_over_the_place { private static $bigArrayOfThings; public function __construct() {On Thu, Feb 14, 2008 at 9:50 AM, Nathan Nobbe <quickshiftin@gmail.com> wrote:Nathan Nobbe schreef:On Thu, Feb 14, 2008 at 6:37 AM, Jochem Maas <jochem@iamjochem.com>wrote:usingwhat you are using is potentially not what you think it is. you area 'static variable' which is not a static class member.actually it pretty much *is* the same - the static class member will exhibit the same behaviour, only the scope is different.you can find the doc on static variables here, http://www.php.net/manual/en/language.variables.scope.php im not sure if their behavior is well defined when they are used inclasses,or objects.behaviour is indentical to usage inside standalone functions.and im certain it was used heavily that way in php4 as well. its also great for those people who dont want to use classes in their php. i mainly avoid it as a matter of preference. all im saying from earlier, is that even if it does work inside class methods, theres no doc out there that gives the green light on such usage (at least not to my knowledge). -nathanthats a gamble since there is no description of how the static keyword behaves inside class member functions. i for one will stick to staticclassvariables and instance variables, and avoid this static variablefeaturealtogether. -nathanJust FYI the static keyword was quite popular in PHP4 for the singleton pattern. You could do something like: function getInstance() { static $instance; if (empty($instance)) {$instance =& new Instance;} return $instance; } I've used it across multiple classes without any real conflicts so it was fine. Of course I wouldn't do such a thing now that I am working in 5, but I just thought I'd throw that out there.
if (!is_array(self::$bigArrayOfThings)) {
$this->complicatedMethodThatFormsArray();
}
}
protected function complicatedMethodThatFormsArray() {
#loads of stuff that would be best not to repeat to often
}
}
#complicatedMethodThatFormsArray is called here
$myclass = new used_all_over_the_place;
function something() {
#complicatedMethodThatFormsArray is NOT called here
$myclass = new used_all_over_the_place;
}
maybe I've gone ot or missed the point of this thread..