如何将$ _SESSION变量传递给函数

时间:2018-01-01 15:10:58

标签: php wordpress function variables session-variables

我正在尝试将$ _SESSION变量传递给WordPress的数据库查询函数。如果我在函数中定义$ _SESSION变量,它可以正常工作。但是当我在全局范围内定义它们并尝试传递它们时,它们不会通过。请查看以下示例。

这将转到下面的函数

$_SESSION['pages'] = $_POST['pages'];

但是当我添加

$pages = $_SESSION['pages'];

$ pages不会传递给函数。

    $_SESSION['pages'] = $_POST['pages']; //passes
    $pages = $_SESSION['pages']; //does not pass

function insertLocalBusinessSchema()
    {
        //include global config  
        include_once($_SERVER['DOCUMENT_ROOT'].'/stage/wp-config.php' );

        global $wpdb;

        // if I try to define this outside of the function it doesn't pass through.
        $pages = implode(',', $_SESSION['pages']);

        $paymentAccepted = implode(',', $_SESSION['paymentAccepted']);

        $table_name = $wpdb->prefix . "schemaLocalBusiness";

        $insert = "UPDATE ".$table_name." SET addressLocality = '".$_SESSION['addressLocality']."', addressRegion = '".$_SESSION['addressRegion']."', postalCode = '".$_SESSION['postalCode']."', streetAddress = '".$_SESSION['streetAddress']."', pages = '".$pages."', paymentAccepted = '".$paymentAccepted."' WHERE id = 1";

        $wpdb->query($insert);

    }

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

$_SESSIONglobal variable,因此您可以从任何地方调用它,而$pages未全局定义,因此您需要将其作为参数传递给函数,如这样:

function insertLocalBusinessSchema($pages)
{
    echo $pages; // the variable is now in the function's scope
}

然后,您将调用函数传递$pages的参数:

insertLocalBusinessSchema($pages);

如果您希望在函数内部使用变量$pages而不将其值作为参数传递,可以使用$GLOBALS PHP super global variable这样做:

// super global variable GLOBALS
$GLOBALS['pages'] = $_POST['pages'];

function insertLocalBusinessSchema()
{
    echo $GLOBALS['pages']; // this also works
}

更多here

或者您可以使用global这样的关键字:

$pages = $_POST['pages'];

function insertLocalBusinessSchema()
{
    global $pages;  // $pages becomes global
    echo $pages;    // this also works
}