Does static variables in php persist across the requests?

后端 未结 3 1271
醉酒成梦
醉酒成梦 2020-12-29 20:19

Static variable gotcha in php

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

3条回答
  •  情书的邮戳
    2020-12-29 20:54

    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 '

    ' . Car::$make . '

    '; unset($c); if (!isset($_SESSION['make'])) { echo '

    ' . Car::$make . '

    '; $c = new Car('Ferrari'); echo '

    ' . Car::$make . '

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

    ' . $_SESSION['make'] . '

    ';

提交回复
热议问题