在PHP中初始化全局变量 - php

在PHP中初始化全局变量是否是一种好习惯?代码片段似乎可以正常工作,但是否最好在函数外部初始化变量(在较大的项目中,出于性能考虑),就像在第二遍代码中一样?

if(isset($_POST["Return"]))Validate();
function Validate(){
    (!empty($_POST["From"])&&!empty($_POST["Body"]))?Send_Email():Fuss();
};
function Send_Email(){
    global $Alert;
    $Alert="Lorem Ipsum";
    mail("","",$_POST["Body"],"From:".$_POST["From"]);
};
function Fuss(){
    global $Alert;
    $Alert="Dolor Sit"
};

function Alert(){
    global $Alert;
    if(!is_null($Alert))echo $Alert;
};

请注意,上面的变量$ Alert尚未初始化。

$Alert;
if(isset($_POST["Return"]))Validate();
function Validate(){
    (!empty($_POST["From"])&&!empty($_POST["Body"]))?Send_Email():Fuss();
};
function Send_Email(){
    global $Alert;
    $Alert="Lorem Ipsum";
    mail("","",$_POST["Body"],"From:".$_POST["From"]);
};
function Fuss(){
    global $Alert;
    $Alert="Dolor Sit"
};

function Alert(){
    global $Alert;
    if(!is_null($Alert))echo $Alert;
};

现在注意。

我感谢任何答案!预先感谢,杰伊

参考方案

在第二个示例中,您仍未声明变量,即行

$alert;

没有为$alert赋值,因此未声明。

如果先声明该变量,则可以更轻松地访问它而不会产生通知:

$alert = '';

if ($alert) {
    //do something with alert
}

PHP-MySQL结果转换为JSON - php

我试图了解如何将MySQL结果转换为JSON格式,以便以后可以在Javascript中使用此JSON来构建HTML表。但是我的代码只是产生大量的空值,我还不明白为什么。$result = mysqli_query($con, "SELECT * FROM Customers"); $test = json_encode($result);…

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

PHP:从函数返回值并直接回显它? - php

这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…

PHP:将数据从二维数组复制到一维数组的最快方法 - php

我有一个巨大的二维PHP数组,带有500万行。$t = [ [ "id" => 1, "name" => "foo" ], [ "id" => 2, "name" => "bar" ] ]; 现在,我必须将此数组的I…

PHP str_replace是否具有大于13个字符的限制? - php

直到击中第13个字符为止。一旦str_ireplace在cyper数组中击中“ a”,str_ireplace就停止工作。数组的大小有限制吗?请记住,如果键入“ abgf”,我会得到“ nots”,但是如果键入“ abgrf”,我应该得到“ notes”,那么我就会得到“ notrs”。机架使我的大脑无法解决。$_cypher = array("n…