【问题标题】:Why does the variable defined in the included script have no value?为什么包含脚本中定义的变量没有值?
【发布时间】:2011-06-21 18:18:22
【问题描述】:

我在 script.php 中有这段代码:

<?php
session_start();

$user_session = $_SESSION['u_name'];

class check_sess {
    public function check_id_session($user_session, $db) { //email
        $stmt = $db->prepare('select id_user from users where email=?');
        $stmt->bind_param('s', $user_session);

        $stmt->execute();

        $stmt->bind_result($id);

        if ($stmt -> fetch()) {
            $id;
            echo $id; // here shows 20 for example
            return true;
        }
        else
        return false;

        $stmt->close();
        $db->close();
    }
}
?>

在 demo.php 我有:

include 'script.php';
$val = new check_sess();
$val-> check_id_session($user_session, $db);
echo $id; //problem here. It is supposed echo 20

为什么我不能echo $id? demo.php中没有输出。

【问题讨论】:

    标签: php session variables


    【解决方案1】:

    了解variable scope。变量$id 在函数外不存在。如果您希望函数返回 $id,请在 if ($stmt -&gt; fetch()) { 条件分支中写入 return $id。然后你可以写:

    include 'script.php';
    $val = new check_sess();
    $id = $val-> check_id_session($user_session, $db);
    echo $id;
    

    【讨论】:

      【解决方案2】:

      你需要返回一个值才能以这种方式访问​​它:

      if ($stmt -> fetch()) {
           return $id; 
      }
      

      除非这不会按您的预期工作。

      您需要先分配$id - 看起来您正在使用某种框架;所以你应该首先将值分配给$id,例如fetch(),然后从方法中返回该值,允许你访问它。

      【讨论】:

        【解决方案3】:

        您的 id 在一个类中,因此在不同的范围内。

        您可以为它编写一个 getter 或将其声明为静态,然后您可以在没有实例的情况下访问它:

        class check_sess {
            static $id;
        ...
            if ($stmt -> fetch()) {
                self::$id = $id;
                echo self::$id; // here shows 20 for example
                return true;
            }
        ...
        }
        

        您现在可以通过

        在代码中的任何位置访问它
        check_sess::$id
        

        【讨论】:

          猜你喜欢
          • 2011-05-03
          • 1970-01-01
          • 2019-06-03
          • 2021-10-24
          • 2019-04-17
          • 1970-01-01
          • 1970-01-01
          • 2013-11-19
          相关资源
          最近更新 更多