如何访问函数内的变量?

时间:2016-04-20 19:27:18

标签: php

我正在编写一个php文件,其中包含我想要执行的任务的功能。其中一些函数需要使用mysql数据库。我已经使用require_once创建了一个单独的db_connections.php文件,该文件已添加到函数文件中。

我可以访问在此文件中创建的PDO对象,但我无法在我的函数中访问此变量。有没有办法访问函数内部的变量?

<?php

require_once ("class.phpmailer.php"); 
require_once ("error_option.php"); 
require_once ("db_connection.php"); //The PDO object has been created here

function processLoginUser($email, $password) {
    //I cant seem to access the pdo object inside functions, but it is accessible outside functions
    $email = trim($email);
    $password = trim($password);
    $checkUserQuery = $dataObject->prepare("CALL sp_CheckLogin()");
    $checkUserQuery->bindParam();
}

3 个答案:

答案 0 :(得分:3)

您可以在调用函数时传递连接对象:

processLoginUser($email, $password, $dataObject);

然后,当您将其添加到参数列表时,它将在函数范围内可访问:

function processLoginUser($email, $password, $dataObject) {
    $email = trim($email);
    $password = trim($password);
    $checkUserQuery = $dataObject->prepare("CALL sp_CheckLogin()");
    $checkUserQuery->bindParam()
}

或者您可以使用闭包(&gt; = PHP 5.3 ),假设在定义$dataObject后调用闭包:

$processLoginUser = function($email, $password) use ($dataObject) {
    $email = trim($email);
    $password = trim($password);
    $checkUserQuery = $dataObject->prepare("CALL sp_CheckLogin()");
    $checkUserQuery->bindParam()
};
$processLoginUser($email, $password); // call the closure as you would a regular function.

或者,您也可以制作$dataObject变量global

function processLoginUser($email, $password) {
    global $dataObject;

    $email = trim($email);
    $password = trim($password);
    $checkUserQuery = $dataObject->prepare("CALL sp_CheckLogin()");
    $checkUserQuery->bindParam()
}

这纯粹是基于意见的,但对于你的情况,我会坚持使用第一个选项:将其作为参数传递给函数。

答案 1 :(得分:1)

你必须写一些像

这样的东西
<?php 
require_once ("class.phpmailer.php"); 
require_once ("error_option.php"); 
require_once ("db_connection.php");

function processLoginUser($email, $password) {
    /**
    global keyword let you use variables out of the scope of 
    your block, however is no recommended
    **/
    global $dataObject;
    $email = trim($email);
    $password = trim($password);
    $checkUserQuery = $dataObject->prepare("CALL sp_CheckLogin()");
    $checkUserQuery->bindParam()

}

我建议您在

之类的内容上重写代码
function processLoginUser($email, $password, $dataObject) {
    $email = trim($email);
    $password = trim($password);
    $checkUserQuery = $dataObject->prepare("CALL sp_CheckLogin()");
    $checkUserQuery->bindParam()    
}

[1] http://php.net/manual/en/language.variables.scope.php

答案 2 :(得分:0)

您遇到了可变范围问题。请参阅:http://php.net/manual/en/language.variables.scope.php

我不建议使用全局变量来解决这个问题。您最好的选择是将变量传递给函数。

function processLoginUser($email, $password, $dataObject) {
    $email = trim($email);
    $password = trim($password);
    $checkUserQuery = $dataObject->prepare("CALL sp_CheckLogin()");
    $checkUserQuery->bindParam()
}