使变量可用于所有类,方法,函数和包含,就像$ _POST一样

oll*_*lli 17 php oop scope

这个问题看起来很简单,但我无法在任何地方找到答案......

在我的php脚本/文件的开头我想创建一个变量.

$variable = 'this is my variable';
Run Code Online (Sandbox Code Playgroud)

我希望这个变量在整个脚本中可用,这样所有类,方法,函数,包含的脚本等都可以简单地将这个变量称为$ variable.

Class MyClass
{
  public function showvariable()
  {
     echo $variable;
  }
}
Run Code Online (Sandbox Code Playgroud)

$ _SESSION,$ _POST,$ _GET变量都表现得像那样.我可以写一个方法并使用$ _POST,它会工作.但是如果我使用我在脚本开头定义的$ variable,它会说"注意:未定义的变量:变量在......"它甚至会说,当我编写一个函数时,而不是类方法. .

我试着写

global $variable = 'this is my variable';
Run Code Online (Sandbox Code Playgroud)

但随后脚本将无法加载..."HTTP错误500(内部服务器错误):服务器尝试完成请求时遇到意外情况."

如何使变量真正全局可访问,如$ _POST?

我为什么需要这个?我特意计划将它用作表单令牌.在页面顶部,我将表单标记生成为$ token,在页面底部我将其存储在会话中.在处理任何表单之前,我检查SESSION令牌是否与POST令牌匹配...并且由于我经常在页面上有多个表单(顶部导航中的登录表单,以及主体中的注册表单),我只是想让它变得方便在每个表单上调用$ token.有时我的formelements是由类或函数生成的,但它们不识别变量并说它没有定义.

oll*_*lli 18

我找到了...... - 我认为这很容易......

我必须使用调用变量

$GLOBALS['variable'];
Run Code Online (Sandbox Code Playgroud)

刚发现它......终于...... http://php.net/manual/en/reserved.variables.globals.php

像8个月后左右编辑:

我刚刚了解了CONSTANTS!

define('name', 'value');
Run Code Online (Sandbox Code Playgroud)

他们只是无法重新分配...我想我也可以使用它! http://www.php.net/manual/en/language.constants.php


But*_*kus 10

只需在任何类或函数之外定义变量.然后global在任何类或函数中使用关键字.

<?php

// start of code

$my_var = 'Hellow Orld';

function myfunc() {
  global $my_var;
  echo $my_var; // echoes 'Hellow Orld';
}

function myOtherFunc() {
  var $my_var;
  echo $my_var; // echoes nothing, because $my_var is an undefined local variable.
}


class myClass {

  public function myFunc() {
    global $my_var;
    echo $my_var; // echoes 'Hellow Orld';
  }

  public function myOtherFunc() {
    var $my_var;
    echo $my_var; // echoes nothing.
  }

}

myFunc(); // "Hellow Orld"
myOtherFunc(); // no output
myClass->myFunc(); // "Hellow Orld"
myClass->myOtherFunc(); // no output

// end of file
?>
Run Code Online (Sandbox Code Playgroud)