PHP中的静态变量 [英] Static variables in PHP

查看:88
本文介绍了PHP中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了有关PHP中静态变量的不同信息,但没有任何信息可以真正解释它是什么以及它如何真正工作.

I have found different information regarding static variables in PHP but nothing that actually explains what it is and how it really works.

我已经读到,在类中使用静态属性时,该类实例化的任何对象都不能使用静态属性,而该类实例化的对象可以使用静态方法?

I have read that when used within a class that a static property cannot be used by any object instantiated by that class and that a static method can be used by an object instantiated by the class?

但是,我一直在尝试研究静态变量在不在类中的函数中的作用.另外,函数中的静态变量的工作方式类似于javascript中的闭包,还是我完全不赞成这种假设?

However, I have been trying to research what a static variable does within a function that is not in a class. Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption?

推荐答案

我已阅读到,在类中使用静态属性时,该类实例化的任何对象都不能使用静态属性

I have read that when used within a class that a static property cannot be used by any object instantiated by that class

这取决于您的意思.例如:

It depends on what you mean by that. eg:

class Foo {
    static $my_var = 'Foo';
}

$x = new Foo();

echo $x::$my_var;  // works fine
echo $x->my_var;   // doesn't work - Notice: Undefined property: Foo::$my_var

并且由类实例化的对象可以使用静态方法???

and that a static method can be used by an object instantiated by the class???

是的,属于该类的实例化对象可以访问静态方法.

Yes, an instantiated object belonging to the class can access a static method.

在类上下文中,关键字static的行为有点类似于其他语言中的静态类变量.声明为static的成员(方法或变量)与该类相关联,而不是与该类的实例相关联.因此,您可以在没有类实例的情况下访问它(例如:在上面的示例中,我可以使用Foo::$my_var)

The keyword static in the context of classes behave somewhat like static class variables in other languages. A member (method or variable) declared static is associated with the class and rather than an instance of that class. Thus, you can access it without an instance of the class (eg: in the example above, I could use Foo::$my_var)

但是,我一直在尝试研究静态变量在不在类中的函数中的作用.

However, I have been trying to research what a static variable does within a function that is not in a class.

此外,函数中的静态变量的工作方式类似于javascript中的闭包,还是我完全不赞成这种假设?

Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption.

在类之外(即:在函数中),static变量是在函数退出时不会丢失其值的变量.因此,从某种意义上讲,是的,它们就像JavaScript中的闭包一样工作.

Outside of classes (ie: in functions), a static variable is a variable that doesn't lose its value when the function exits. So in sense, yes, they work like closures in JavaScript.

但是与JS闭包不同,在同一函数的不同调用之间维护的变量只有一个值.在PHP手册的示例中:

But unlike JS closures, there's only one value for the variable that's maintained across different invocations of the same function. From the PHP manual's example:

function test()
{
    static $a = 0;
    echo $a;
    $a++;
}

test();  // prints 0
test();  // prints 1
test();  // prints 2

这篇关于PHP中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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