簡體   English   中英

Php 獲取 function 之外的全局變量的值

[英]Php get value of global var outside function

我在 php 中有這個測試 function:

funtion drop() {
    global $test_end;

    if(file_exists("test.php")) {
        $ddr="ok";
    }

    $test_end="ready";
}

例如,我知道如果我調用drop() ,它會給我“ok”。

My question is this: if I define a global variable inside a function, how can I output the value of this variable inside the function, and also outside of the function when executed?

例如,調用drop() ,然后運行echo $test_end; 在 function 之外獲取值:

drop();
echo $test_end;

不要使用全局變量,這是一個糟糕的設計,因為它會使您的代碼混亂且難以閱讀。 還有更好的選擇。

給定您的簡單示例,您可以從方法中返回值:

function drop()
{
    if(file_exists("test.php"))
    {
        $ddr="ok";
    }

    $test_end="ready";
    return $test_end;
}

$test_end = drop();

如果您有更復雜的情況並且由於某種原因無法返回值,請通過使用前綴&來通過引用傳遞變量:

funtion drop(&$test_end)
{
    if(file_exists("test.php"))
    {
        $ddr="ok";
    }

    $test_end="ready";
}

$test_end = null;
drop($test_end);
echo $test_end; // will now output "ready"

通過引用傳遞也不是一個很好的模式,因為它仍然會讓你的代碼混亂。

更多關於為什么全局變量不好

問題是,如果我正在查看您的代碼,而我看到的只是:

drop();
echo $test_end;

我不知道 $test_end 是如何設置的或它的價值是什么。 現在假設您有多個方法調用:

drop();
foo();
bar();
echo $test_end;

我現在必須查看所有這些方法的定義以找出 $test_end 的值是什么。 這在較大的代碼庫中成為一個非常大的問題。

全局變量不是一個糟糕的設計模式。 但是有很多全局變量通常是糟糕編程的標志。 你應該盡量減少它們。

要檢索該值,您只需引用它:

 function set()
 {
    global $test_end;
    $test_end="ready";
 }
 function show()
 {
    global $test_end;
    print "in show() value=$test_end\n";
 }
 function noscope()
 {
     print "in noscope() value=$test_end\n";
 }
 $test_end="begin";
 print "In global scope value=$test_end\n";
 show();
 noscope();
 set();
 print "after calling set()\n";
 print "In global scope value=$test_end\n";
 show();
 noscope();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM