Variable & Variable Scope | PHP Fundamentals

WBOY
Release: 2024-07-19 02:18:10
Original
541 people have browsed it

Variable & Variable Scope | PHP Fundamentals

Create Variable in PHP

The rules when you create variables in PHP:

  1. Variable declaration with dollar ($) followed by variable name
  2. Variable name must start with a letter or underscore (_)
  3. Variable name is case-sensitive

Valid variables:

$name = "Gunawan"; //valid
$Name = "Gunawan"; //valid
$_name = "Gunawan; //valid
Copy after login

Not valid variables:

$4name = "Gunawan"; //not valid
$user-name = "Gunawan"; //not valid
$this = "Gunawan"; //not valid
Copy after login

Variable Scope

PHP has 3 variable scopes:

  1. Global
  2. Local
  3. Static

Global scope

$name = "Gunawan";

function get_name() {
echo $name; // not valid
}

get_name();
Copy after login

To access a global variable within a function you must declare a global variable with the keyword 'global' within a function.

$name = "Gunawan";

function get_name() {
global $name;
echo $name; // valid
}

get_name();
Copy after login

Use Array GLOBALS to Access Global Variable

The second way to access global variables is to use a global array.

$name = "Gunawan";

function get_name() {
echo $GLOBALS['name']; // valid
}

get_name();
Copy after login

Static Variable

function test() {
static $number = 0;
echo $number;
$number++;
}
Copy after login

Variable Super Global in PHP:

  1. $GLOBALS
  2. $_SERVER
  3. $_GET
  4. $_POST
  5. $_FILES
  6. $_COOKIE
  7. $_SESSION
  8. $_REQUEST
  9. $_ENV

Download my repository php fundamental from my github.

The above is the detailed content of Variable & Variable Scope | PHP Fundamentals. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
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!