PHP:使用包含文件中的全局变量

时间:2013-09-02 07:49:40

标签: php include global-variables

有很多类似的问题,但我无法让它工作: 我尝试在包含文件中使用全局变量,如下所示:

included.php:

<?php
  function some_function()
  {
     $GLOBALS['username'] = $_SERVER["REMOTE_USER"];
  }
?>

first.php:

<?php
  include 'included.php';
  some_function()

  echo '<p>Hello ' . $GLOBALS['username'] . '!'</p>'
?>

second.php:

<?php
  include 'included.php';

  echo '<p>Hello ' . $GLOBALS['username'] . '!'</p>'
?>

first.php的输出工作得很好,但是在second.php中有一个错误:

  

注意:未定义的索引:第36行的/var/www/students/reservations.php中的student_firstname

所以我的目标是在我的项目中使用这个全局变量'username',我不想每次都调用some_function(),因为SQL查询有更多的变量,所以这需要太长时间。 / p>

有没有一种很好的方法可以做到这一点,或者你能用另一种方式推荐我吗? 谢谢!

2 个答案:

答案 0 :(得分:0)

为此目的,有一个关键字global。但它被认为是一种非常糟糕的做法并且违反了封装等。

$username = "Test" ;

function some_function(){
  global $username ;  //Put a global variable into current space.
  echo $username ;    //Now you can access the global variable.
}

P.S。学会将变量作为参数传递给函数,因为它会让你的生活变得非常轻松。

答案 1 :(得分:-1)

您可以使用PHP会话, 例如,在您的索引页面上有代码;

<?PHP  
session_start();
$_SESSION['username']=$_SERVER["REMOTE_USER"];
?>

然后在您需要放置的所有页面之上;

<?PHP  
session_start();
?>

在标签上方。

然后您只需

即可调用用户名
<?PHP echo $_SESSION['username']; ?> and that will display their username.

来源:3年来一直是PHP / HTML / CSS开发人员。

相关问题