在普通的php函数中使用static关键字是否存在任何问题? [英] Are there any issues with using static keyword in a plain php function?

查看:43
本文介绍了在普通的php函数中使用static关键字是否存在任何问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

<?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;
?>

//输出:ID集:5 5 5

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

http://codepad.org/jg2FR5ky

因此,大概重复调用以获取用户ID只是简单地返回仍在内存中的ID.我不知道这是否是php函数的惯用用法.有点像单例,除了不是OO,而且我从未听说过或看到其他人在使用它,所以我想知道以这种方式使用静态是否有缺点,或者是否应该了解一些陷阱功能中更复杂的静态用例.

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 problems might I encounter with this type of usage of statics?

推荐答案

我认为这种方法没有任何问题-实际上,我自己经常使用它,因为它的寿命很短缓存mecanism ",当您拥有一个被多次调用的函数时,它非常有用/有用,并且会进行大量计算(例如数据库查询),以始终为该函数返回相同的值给定的脚本执行.

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.

我知道我并不是唯一一个这样做的人:例如,Drupal经常使用这种机制-作为缓存.

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.

这篇关于在普通的php函数中使用static关键字是否存在任何问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆