PHP variable,
PHP Variables
- The variable name starts with the $ symbol, followed by the variable name
- The variable name must start with a letter or underscore.
- Variable names can only contain letters, numbers, and underscores (A-z, 0-9, and _)
- Variable names cannot contain spaces
- Variable names are case sensitive
PHP has no command to declare Variables
The variable is created when it is assigned a value for the first time.
<?php$txt="Hello world!";$x=5;$y=10.5;?>
PHP is a weak language
PHP automatically converts the variable to the correct data type based on the value of the variable.
PHP variable scope
- Local
- Global
- Static
- Parameter
Global and local scope
<? Php $ x = 5; // global variable function myTest () {$ y = 10; // local variable echo "<p> test function internal variable: <p> "; echo "variable x: $ x"; echo "<br>"; echo "variable y: $ y"; // output 10} myTest (); echo "<p> test function outer variables: <p>"; echo "variable x: $ x"; // output 5 echo "<br> "; echo "variable y: $ y";?>
1. The global keyword is used to access global variables in the function.
<? Php $ x = 3; $ y = 5; function myTest () {global $ x, $ y; $ z = $ x * $ y;} myTest (); echo "$ z"; // output 15?>
The above instance can be written as this
<? Php $ x = 5; $ y = 10; function myTest () {$ GLOBALS ['y'] = $ GLOBALS ['X'] * $ GLOBALS ['y'];} myTest (); echo $ y; // output 50?>
2. static scope (when a function is complete, all its variables are usually deleted, but you do not want to delete it. You need to use the static keyword for the first declaration)
<?phpfunction myTest(){ static $x=0; echo $x; $x++;} myTest();//0myTest();//1myTest();//2?>