首页 > 解决方案 > Static variables across all scripts/sessions php

问题描述

On a php web page, in the beginning of the PHP code I declare and set a lot of variables which are not altered during the execution of the script.

Each time a user visits the page, the script is executed, and I guess the values of the variables are stored in the RAM ? So if 100 visitors are visiting the page simultaneously, the same static variables are stored in the RAM 100 times ?

Is there a way to store them in the RAM only once and have the possibility to use their values in any script without declaring them in each script ? Like PHPs superglobals.

For clarities sake: the only reason I am asking this is to realize a performance increase (by not loading the same things X times in the RAM). If the way(s) to do what I ask do not save any memory or have other positive impact on performance, I see no reason to change my current approach.

Thanks !

标签: php

解决方案


The concept which you seem to be juggling with can be summarized as:

Prevent memory overhead by storing and sharing PHP variables between PHP processes so that they do not have to be re-initialized per script.

The short answer is that this is simply not possible due to the scoping nature of PHP. Every time a PHP script is executed it needs to bring in a copy of the variable into it's own execution scope.

By far the biggest culprit for slowing down a server is disk access time.

If you have:

vars.php`

<?php
$var1 = 'hi';
$var2 = 20;
$var3 = 99;

and

index.php

<?php
require_once('vars.php');

then the most intensive part of index.php is reading vars.php from the disk.

OpCache solves the issue of reading from disk by caching the instructions of vars.php into memory so that next time vars.php is requested it can just serve up what it has in memory and give a copy to the current PHP thread.


There exists a memcache class (and many other solutions) which can store variable values in a dedicated data bank but it requires the setup of a memcache server.

The issue is that this still will not prevent memory overhead because calling memcache::get( 'someVar' ); still requires bringing that variable into the current memory scope so that PHP can operate on it.


One more thing...

Hardware is cheap, programmers are not. Unless you are running into some severe uncontrolled memory issues which are causing system crashes then it is always cheaper to add RAM than it is to have a programmer spend days trying to solve a non-issue.

However, if you are looking to contribute to PHP's actual speed and memory consumption then you'll need to learn some C programming and dig into the core.


推荐阅读