用PHP创建变量全局?

时间:2011-01-22 19:38:51

标签: php mysql variables global

需要将$ courseInfo和$ row全局化,以便它们可用于在标题DIV中打印行详细信息。

不知道如何做到这一点。任何帮助都会很棒。

<?php 


// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);

// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");

if (mysql_num_rows($courseCheck) == 1) {

    $checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");

    if (mysql_num_rows($checkMember) == 1) {

        ?>
        <html>
        <head>
            <!-- Style Sheets -->
            <link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
            <link rel="stylesheet" href="style/style.css" type="text/css" media=screen />
        </head>
        <body>

        <?php
        if ($_SESSION['LoggedIn'] == 1){ 

            $courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
            $row = mysql_fetch_assoc($courseInfo);

        ?>

            <div id="container">
                <div id="side">
                    <?php include("lib/sidebar.php"); ?>
                </div>
                <div id="main">
                    <div id="mainbox">
                        <div id="header"><b><?php echo $row['CourseName']; ?></b></div>
                        <p>Hello world, this is a test.</p>
                    </div>
                </div>
            </div>
            <div class="clear"></div>

            <?php
            } 
        else { 
            echo "Not logged in.";
        }

    }

    else {
        echo "You are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>
</body>

3 个答案:

答案 0 :(得分:4)

我认为他们已经全球化了。 "PHP does not have a block-level scope."

答案 1 :(得分:1)

您可以将它们存储在会话变量中,类似于$_SESSION['LoggedIn']

答案 2 :(得分:0)

您还可以使用php变量$ GLOBALS使您的变量在所有范围内都可见,但我不建议将其用于此类任务。另外,要注意 - $ GLOBALS包含像$ _POST和$ _GET这样的超级全局,你应该记住这一点。迭代它。此外 - 当您可以在函数中访问$ _GET和$ _POST时,范围较小的范围仍需要使用$ GLOBALS来访问自定义范围。

此类行为的示例:

<?php
error_reporting(-1);

$GLOBALS['_customVar'] = 'foobar';
$GLOBALS['_GET']['id'] = 'myId';

    function myFnc() {
    echo $_customVar;
    }

    function myFnc2() {
    echo $_GET['id'];
    }

myFnc();
myFnc2();

?>