如何在PHP中更改静态变量值? [英] How do I change a static variables value in PHP?

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

问题描述

这是我要完成的工作的简化版本:

This is a simplified version of what I want to accomplish:

在我的脚本中,我想要一个每次执行脚本时都会更改为true和false的变量.

In my script I want a variable that changes true and false everytime the script is executed.

<?php
    static $bool = true;

    // Print differente messages depending on $bool
    if( $bool == true )
        echo "It's true!";
    else
        echo "It's false!";

    // Change $bools value
    if( $bool == true )
        $bool = false
    else
        $bool = true;
?>

但是显然我在做什么是错误的.变量$bool始终为true,我尚未完全掌握我假定的静态变量的概念.我在做什么错了?

But obviously what I'm doing is wrong. The variable $bool is constantly true and I haven't fully grasped the concept of static variables I presume. What am I doing wrong?

推荐答案

PHP无法在请求之间保留变量值.这意味着每次调用脚本时,$bool-变量将设置为true.如果要保留两次请求之间的值,则必须使用 sessions 或,如果您希望变量在会话之间共享,则可以使用某些缓存机制,例如 APC Memcache .

PHP is not able to keep variable values between requests. This means that each time your script is called, the $bool-variable will be set to true. If you want to keep the value between requests you have to use sessions or, if you want the variable shared between sessions, some caching mechanism like APC or Memcache.

此外,static在PHP中用于声明在类级别共享的变量.因此,它可以在类中使用,并且可以像self::$variableName;Foo::$variableName

Also, static is used in PHP to declare a variable shared on the class level. It is thus used in classes, and accessed like self::$variableName; or Foo::$variableName

您可以在此处阅读有关静态属性的更多信息.从文档中:

You can read more about static properties here. From the docs:

将类属性或方法声明为静态可以使它们无需类的实例化即可访问.实例化的类对象无法访问声明为静态的属性(尽管可以使用静态方法).

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

此外,请注意,自PHP 5.3起,单词static已被重载,还可以用来表示

Also, note that the word static has been overloaded since PHP 5.3, and can also be used to denote Late Static Binding, by use of static::

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

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