

When we call the myTest() function and output the values of two variables, the function will output the value of the local variable $y, but not the value of $x, because the $x variable is defined outside the function and cannot be used inside the function, if To access a global variable within a function, use the global keyword. The $x variable is declared outside the function, so it's a global variable, and the $y variable is declared inside the function so it's a local variable. In the above example the myTest() function defines the $x and $y variables.

Variables declared inside a PHP function are local variables and can only be accessed inside the function: Test variables inside the function:" Įcho "Test variables outside the function:" To access a global variable within a function, use the global keyword. Except functions, global variables can be accessed by any part of the script. Variables defined outside all functions have global scope. The scope of a variable is the part of the script where the variable can be referenced/used.

In strongly typed programming languages, we must declare (define) the type and name of a variable before using it. PHP will automatically convert the variable to the correct data type based on the value of the variable. In the example above, we noticed that it was not necessary to declare the data type of the variable to PHP. Note: When you assign a text value to a variable, put quotation marks around the text value. In the execution of the above statement, the variable txt will hold the value Hello world! and the variable x will hold the value 5. PHP has no command for declaring variables.Ī variable is created the first time you assign to it:
