开发者

Making Variables Global in PHP?

Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.

Don't have a clue how to do this. Any help would be great.

<?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 "开发者_如何学JAVAYou are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>
</body>


I think they're already global. "PHP does not have a block-level scope."


You could store them in session variables, similarly to your $_SESSION['LoggedIn']


You could also use php variable $GLOBALS for making your variables visible in all scopes but I would not recommend it for this kind of task. Also, beware - $GLOBALS contains superglobals like $_POST and $_GET, you should keep that in mind, when ie. iterating over it. Furthermore - when you can access $_GET and $_POST in functions, that have smaller scope you still have to use $GLOBALS to access custom ones.

Example for this kind behaviour:

<?php
error_reporting(-1);

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

    function myFnc() {
    echo $_customVar;
    }

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

myFnc();
myFnc2();

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜