Does static variables in php persist across the requests?

允我心安 提交于 2019-11-28 22:30:34

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.

Example:

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

Static variables are only applicable to one single request. If you want data to persist between requests for a specific user only use session variables.

A good starter tut for them is located here: http://www.tizag.com/phpT/phpsessions.php

If you begin working with complex data sets across sessions you may want to look into storing data in objects that get serialized to the database and drawn out on session restore.

Variables in PHP aren't meant to be persistent. The flow of your application (the stack) is executed start to finish on each page run. There is nothing living in the background that continues your logic or application. The closest thing is a session but you do not want to store information like db access etc. in there.

Your database configurations should be in some sort of config or environment file that are accessed one time to connect to the database, once a connection has been made you can simply query whenever needed and use the connection handle to identify what connection to use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!