Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

Does static variables in php persist across the requests?

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.

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

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 ?

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

question from:https://stackoverflow.com/questions/520132/does-static-variables-in-php-persist-across-the-requests

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...