php无法访问函数之外的全局变量

时间:2015-08-19 03:29:01

标签: php variables global

我试图访问$error_message函数之外的PHP变量$success_messagecheck_fields。它不起作用。我知道不建议使用全局变量。我只需要一种方法来返回变量和布尔值truefalse或全局获取它们。

function check_fields($pattern,$post,$minlength,$maxlength,$name_of_field)
{
    global $error_message;
    global $success_message;
    $length_of_string = strlen($post);
    if(isset($post))
    {
        if(preg_match($pattern,$post))
        {
            if($minlength < $length_of_string || $maxlength > $length_of_string)
            {
                return true;
                $success_message .= $name_of_field . ' checked successfully...';
            }else
                {
                return false;
                $error_message .= $name_of_field . ' must be less than ' . $maxlength . 'and greater than' . $minlength;
                }

        }else 
        {
        return false;
            $error_message .= $name_of_field . ' was not correct, please enter this information again <br />';
        }

    }else
    {
        return false;
        $error_message .= $name_of_field . ' was not set <br />';
    }
}

2 个答案:

答案 0 :(得分:0)

您可能需要在函数外部创建变量。 (由于您不包含该代码,我无法判断您是否已经完成此操作。)

您还需要在“返回false”之前将邮件放入这些字段中。在您发布的代码中,大多数消息分配语句都无法访问。

$error_message = '';
$success_message = '';

function check_fields($pattern,$post,$minlength,$maxlength,$name_of_field)
{
    global $error_message;
    global $success_message;
    $length_of_string = strlen($post);
    if(isset($post))
    {
        if(preg_match($pattern,$post))
        {
            if($minlength <= $length_of_string)
            {
                //return true;
                $success_message .= $name_of_field . ' checked successfully...';
                return true;
            }else
                {
                //return false;
                $error_message .= $name_of_field . ' must be less than ' . $maxlength . 'and greater than' . $minlength;
                return false;
                }

        }else 
        {
            //return false;
            $error_message .= $name_of_field . ' was not correct, please enter this information again ';
            return false;
        }

    }else
    {
        //return false;
        $error_message .= $name_of_field . ' was not set';
        return false;
    }
}

答案 1 :(得分:0)

所有好的答案和你们都很棒,但到目前为止似乎最可行的那个只是调整布尔值真假语句的优先级。我想代码就像退​​出之前能够记录错误信息。谢谢你们所有人,但我和你一起回答的是Ryan Vincent。