在 php 中仅创建一次变量

create variable only once in php

我一直在寻找一种方法 运行 一段代码只在 php 中出现一次。我想在网页的开头创建并设置一个变量,每当我调用该文件时,代码都会忽略该行。

我发现 this 其中基本上有两个建议:setting a session variablecreating a lock file 我不想这样做,因为可能同时有很多用户,我他们每个人都需要一个锁文件。

我尝试了第一个选项,但它不起作用。

这是我的两个文件:

config.php

<?php 
     if (at the beginning){
         $variable = something
         echo 'hello';
     }
     else
          do something
?>

second.php

<?php
     require_once 'config.php'    
     //do some other stuff
?>

每当调用 second.php 时,它都会在网页中打印 'hello',因此 if (at the beginning) returns true 即使它不在开头。请注意,我检查是否在开头 if(!isset($_SESSION['done'])){ $_SESSION['done'] = 'done'; }

我想知道我的错误是什么,我该如何解决这个问题。任何帮助表示赞赏。

config.php 的程序流程应该是:

<?php 
     session_start();

     if (!isset($_SESSION['done'])) {
         $_SESSION['done'] = 1;
         echo 'hello';
     }
     else {
         // do something
     }
?>