doujia6433 2011-06-21 18:18
浏览 49
已采纳

为什么包含的脚本中定义的变量没有值?

I have this code in 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();
    }
}
?>

and in demo.php I have:

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

Why can't I do echo $id? There is no output in demo.php.

  • 写回答

3条回答 默认 最新

  • duanjian4331 2011-06-21 18:21
    关注

    Read about variable scope. The variable $id does not exist outside the function. If you want the function to return $id, write return $id in the if ($stmt -> fetch()) { condition branch. You can then write:

    include 'script.php';
    $val = new check_sess();
    $id = $val-> check_id_session($user_session, $db);
    echo $id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决