开发者

Are there any issues with using static keyword in a plain php function?

For example:

<?php
    function get_current_user_id(){
        static $id;
        if(!$id){
            $id = 5;
            echo "Id set.";
        }
        return $id;
    }


$id = get_current_user_id();

$id2 = get_current_user_id();

$id3 = get_current_user_id();

echo "IDs: ".$id." ".$id2." ".$id3;
?>

//Output: Id set.IDs: 5 5 5

http://codepad.org/jg2FR5ky

Thus presumably repeated calls to get the user id just do a simple return of an id still in memory. I don't know if this is idiomatic use of php functions, though. It's kinda like a singleton, except not OO, and I've never heard of or seen other people using it, so I'm wondering if there are downsides to using statics in this manner, or if there are gotchas I should be aware of for more complex use cases of statics in functions.

So, what proble开发者_运维技巧ms might I encounter with this type of usage of statics?


I don't think there is anything wrong with that approach -- actually, I use it myself quite often, as a "very short-lifetime caching mecanism", which is great/useful when you have a function that is called a lot of times, and does heavy calculations (like a database query) to always return the same value for a given execution of a script.

And I know I'm not the only one doing this : Drupal, for instance, uses this mecanism a lot -- as a cache, too.

The only "problem" I see is when you want to "clear the cache" : you have to pass an additionnal parameter to the function ; and code a couple of lines to "reset" the static cache when that parameter is set.


Static is fine in this context and even works in PHP 4 (not that that should play a role anymore, but still).


I don't think there's anything explicitly wrong with this approach. I think it's just that most people who implement caching are probably using a more complicated setup for doing so than a simple static variable. If it works, use it, that's why it's there.

I can't think of a better way to implement caching in a function that computes a sequence of numbers. For example, say you were computing numbers in the Fibonacci sequence. Each successive call, without the use of caching, would generate a new list and re-calculate numbers the program has already seen. Using a static variable, you could simply return an element of the cached collection of n is smaller than the length of the cache, and it would be trivially simple to computer higher numbers n of fib(n), since you would be able to start with the last two elements at the end of your cache. Implementing this as a singleton would be overkill.


I'm no so sure the static keyword is valid in that context. (althought I may be totally wrong) Traditionally, values like that are either passed by reference into the function or you would use the global keyword to access a variable in the global scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜