-2

When I test an easy PHP program , I found that there is a strange problem. The code is in fllow:

<?php

$a = "abc";
function Test()
{
    global $a;
    $b .= $a."e";
    return $b;
}

echo Test();

As I know,it is legal.But Visual Studio Code tells me that the $b is Undefined variable. enter image description here

At the same time, the program can run successfully with the output:abce

enter image description here

Anybody can help me? I want to know the reason.

nice_dev
  • 17,053
  • 2
  • 21
  • 35
  • 1
    You need to look closer to the `.=` operator you are using. It explains, why you're getting a Warning. And no, it is nowhere legal. Neither using .= or global. it must be function Test($a) instead of using global – Your Common Sense Dec 31 '22 at 07:29
  • Another reason why code needs to be indented properly(if you were already aware of `.=`) – nice_dev Dec 31 '22 at 07:31
  • 1
    @YourCommonSense What's illegal about using `global` like that? – Joseph Sible-Reinstate Monica Dec 31 '22 at 07:31
  • There are 2 ways to do it, first, don't use global because it's not make any sense you can just use string and passed into a variable. But if you want to use global then don't append just use $b = "ABC"; – Sajid Ijaz Dec 31 '22 at 08:18

1 Answers1

-1

It's because you used .= instead of just =. That means the RHS gets appended to the LHS, which means it's expected to have been set before. If you didn't expect $b to exist before, then you should have just used =.