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

问题描述 投票:0回答:1

我试图将我的$ _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);

    }

感谢您的帮助!

php wordpress function variables session-variables
1个回答
1
投票

$_SESSION是一个global 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
}
© www.soinside.com 2019 - 2024. All rights reserved.