Why does the variable defined in the included script have no value?
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.ph开发者_JAVA百科p.
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;
You need to return a value to access it in this way:
if ($stmt -> fetch()) {
return $id;
}
Except that won't work as you intended.
You need to assign $id
first - and it looks like you're using some kind of framework; so you should first assign the value to $id
, as a result from say, fetch()
, and then return that value from the method, allowing you to access it.
your id is within a class and therefore in a different scope.
You can either write a getter for it or declare it as static, then you can access it without an instance:
class check_sess {
static $id;
...
if ($stmt -> fetch()) {
self::$id = $id;
echo self::$id; // here shows 20 for example
return true;
}
...
}
You can now access it anywhere in your code via
check_sess::$id
精彩评论