php - Questions about defining variables
过去多啦不再A梦
过去多啦不再A梦 2017-06-07 09:23:08
0
5
695

I am a beginner. I use phpstorm to write the following code at home and it will run without error.
The code is as follows:


<?php
$x=5; // Global variable
function myTest()
{

$y=10; // 局部变量
echo "<p>测试函数内变量:<p>";
echo "变量 x 为: $x";
echo "<br>";
echo "变量 y 为: $y";

}
myTest();
echo "<p>Test function external variable:<p>";
echo "Variable x is: $x";
echo "
";
echo "Variable y is: $y";
?>


But when I go to work, the browser reports this prompt, as follows:
Variables in the test function:
Notice: Undefined variable: x in F:WEBDEVELOPIndex.php on line 8
The variable x is:
Variable y is: 10
Test function external variable:
Variable x is: 5
Notice: Undefined variable: y in F:WEBDEVELOPIndex.php on line 18
Variable y is:

Question:
When I read the PHP tutorial, it was said that $ can be used to define variables, but it was prompted that the x variable has not been declared. Can someone please explain it to me? Thanks

过去多啦不再A梦
过去多啦不再A梦

reply all(5)
女神的闺蜜爱上我
  1. I guess that the error is not reported at home but the error is reported by the company because of the different error level settings of PHP. You can try adding the following code at the beginning of the code:

    error_reporting(E_ALL ^ ​​E_NOTICE);//Except E_NOTICE, report all errors
    This is set dynamically, you can also set it in php.ini, the specific method can be found on Baidu;

  2. The variables in the function are closed to the outside world. If they are set outside, they cannot be used inside. This has nothing to do with the PHP version. It is explained in detail upstairs.

迷茫

PHP global variables are explained in detail here

To define global variables externally, when using them inside a function, you need to use the global keyword, which is a grammatical requirement, or use the $GLOBAL array

女神的闺蜜爱上我

You need to declare it as a global variable, global $x; this way

巴扎黑

You can search for the keyword "scope". The variable scope of each language is different and can be understood by comparison.

曾经蜡笔没有小新

Look at the PHP version you tested and the PHP version in your working environment. I'm not sure about the new version. The scope of global variables in 5.3 and 5.6 does not include the inside of the function, so it is normal that the function cannot recognize $x, because there is no such variable in the scope of the function

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!