Home  >  Q&A  >  body text

Why does global not work in functions?

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>php.cn</title>

</head>

<body>

<?php

$x=5;

$y=6;

function test(){

global $x,$y;

$y= $x $y;

}

test();

echo $y;

?>

</ body>

</html>

After execution, the result is 6, shouldn’t it be 11? I checked that $x has no value

许云龙许云龙2109 days ago1651

reply all(4)I'll reply

  • 明日边缘

    明日边缘2019-03-01 16:22:59

    You only used the value of the global variable in the method, and the value of the global variable did not change.

    reply
    0
  • 失去过去

    失去过去2019-02-05 20:24:50

    Use the $GLOBAL super global function to print the data and you will know how much the data is

    reply
    0
  • 过客

    过客2019-02-03 09:53:02

    //是可以正常显示11呀,不行你复制本地测试一下看看
    $x=5;
    $y=6;
    function test(){
    global $x,$y;
    $y=$x+$y;   //11= 5 + 6
    }
    test();
    echo $x;	//5
    echo "<br>";
    echo $y;	//11


    reply
    0
  • Cancelreply