Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pc579's avatar
Level 1

PHP global - strange behavior

I got a strange behavior in a Laravel project. I reduce my code and get this strange result.

Laravel 8 / PHP Version 7.4.21

The code

<?php
	$v='aaa';
	echo "v = ",$GLOBALS['v'] ?? "KO","<br>";
	MyFct('Test2');
	phpinfo();
	exit;
	function MyFct($txt) {
		global $v;
		echo "v=$v<br>";
		echo "v = ",$GLOBALS['v'] ?? "KO","<br>";
	}

The result

v = KO					aaa expected
v=							aaa expected
v = KO					aaa expected

I expected to find st in the phpinfo but I can't figure out which parameter could produce this ...

I tested this code in cli, it works fine.

0 likes
4 replies
pc579's avatar
Level 1

@snapey & @martinbean

I know this*, it's an old part of code (more than 10 years old) and it uses some/few global variables* well documented. In short term It's not an option to refactor all (too works to do). I am trying to put this code in Laravel project.

Thanks to your answers, it confirms that I have to do more tests ...

I did one more test by executing this code in a simple php page outside of my Laravel project on the same server, it works ... the pb seems to come with Laravel ... to be continued

*these variables could be in .env that, if I am not wrong, can conduct to the same bad coding practices?

pc579's avatar
pc579
OP
Best Answer
Level 1

More tests

  • works in public/index.php
  • does not work directly in a closure function in routes/web.php ... that's normal

Explanation

  • the Laravel code is executed from the route scripts (routes/web.php, ...=) via function ... that means that declaring a variable in Laravel (contraoler, view, ...) never conducst to a variale in global scope!

Please or to participate in this conversation.