为全局变量php赋值时获得意外输出


Getting unexpected output while assigning a value to global variable php

我试图执行这个php程序,但得到了意外的输出

<?php
$abc;
function test(){
    $abc="world";
}
test();
echo "hello ".$abc;?>

Output : hello
Expected output : hello world

我是php的新手。请任何人告诉我我在这个代码中犯了什么错误
我知道,如果我在function test()的范围之外给$abc="world",它就会起作用
我应该怎么做才能为函数中的全局变量赋值?

您可以在类中定义$abc,然后使用$this访问它。

 <?php 
  class xyz {
   public $abc = '';
   function test(){
    $this->abc = "world";
  }
 }
$a = new xyz();
$a->test();
echo "hello ". $a->abc;
?>

演示

使用全局变量通常被认为是一种不好的做法,但您可以使用global关键字来做到这一点。

<?php
$abc;
function test(){
    global $abc;
    $abc="world";
}
test();
echo "hello ".$abc;?>

test中的$abc是本地的。如果要访问全局变量,必须在函数中使用global $abc来指定它。

请参阅此处

您需要告诉PHP编译器您想要使用全局$abc变量,如:

$abc;
function test() {
    global $abc;
    $abc="world";
}
test();

因为php中的变量范围与javascript不同,例如,因为您可能已经从那里跨过去了。

在PHP中,函数中定义的任何变量自然都是该函数的私有变量。

您在test()中编辑的$abc与全局$abc不同。以您想要的方式修复您的代码:

<?php
$abc;
function test(){
    global $abc;
    $abc="world";
}
test();
echo "hello ".$abc;
?>