php中的静态变量是否在请求中持续存在? [英] Does static variables in php persist across the requests?

查看:79
本文介绍了php中的静态变量是否在请求中持续存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Java背景,最近已为一个项目切换到php. 我在php中发现了一种意外行为.

I am from Java background and have switched to php for one project recently. I have found one unexpected behaviour in php.

设置为某个静态变量的值是 不能在整个中保持不变 请求.

Value set to some static variable is not staying persistent across the requests.

我不确定这是否是预期的行为.因为在Java中,您始终可以在请求中保留非常常用的变量或说出诸如dbname,hostname,username,password之类的常量,因此您不必总是从本地属性文件中读取它们.

I am not sure if this is the expected bahaviour. Because in java , you can always persist very commonly used variables or say constants like dbname,hostname,username,password across the requests so that you don't have to read them always from local property files.

这种行为正常吗?如果是正常的话,那么是否有其他方法可以在请求中保留分配给变量的值?

Is this behaviour normal ? And if it is normal then is there any alternative by which I can persist values assigned to variables across the requests ?

有人可以建议我用php更好的方法吗?

Can someone suggest me a better way of doing this in php?

推荐答案

不,虽然静态变量将保留在当前请求中,但您需要将其添加到会话中以在请求中保持其价值.

No, while a static variable will stay for the current request you'll need to add it to a session to persist it's value across requests.

示例:

session_start();

class Car {
    public static $make;
    public function __construct($make) {
        self::$make = $make;
    }
}

$c = new Car('Bugatti');
echo '<p>' . Car::$make . '</p>';
unset($c);

if (!isset($_SESSION['make'])) {
    echo '<p>' . Car::$make . '</p>';
    $c = new Car('Ferrari');
    echo '<p>' . Car::$make . '</p>';
}

$_SESSION['make'] = Car::$make;

echo '<p>' . $_SESSION['make'] . '</p>';

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

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