Variable in PHP

Variable in PHP

All kind of Variable in PHP at a glance

In PHP, variables can be categorized based on their scope, data type, and origin. Here are some common categories of PHP variables:

  1. Local Variables:

    • Declared and used within a function or block of code.

    • Limited to the scope in which they are defined.

    function exampleFunction() {
        $localVariable = "I am local";
        // $localVariable is only accessible within this function
    }
  1. Global Variables:

    • Defined outside of any function or code block.

    • Accessible from any part of the script, including functions.

    $globalVariable = "I am global";

    function exampleFunction() {
        global $globalVariable;
        // $globalVariable is accessible within this function
    }
  1. Superglobals:

    • Global variables predefined by PHP that are accessible from any part of the script.

    • Examples include $_POST, $_GET, $_SESSION, $_SERVER, etc.

  2. Static Variables:

    • Retain their value between function calls.

    • Defined using the static keyword inside a function.

    function exampleFunction() {
        static $staticVariable = 0;
        $staticVariable++;
        echo $staticVariable;
    }
  1. Constants:

    • Values that remain the same throughout the script.

    • Defined using the define() function or the const keyword.

    define("PI", 3.14159);
    const MAX_VALUE = 100;
  1. Data Type-based Categories:

    • Scalars: Hold a single value (e.g., int, float, string, bool).

    • Arrays: Hold an ordered collection of values.

    • Objects: Instances of user-defined classes.

    • Resources: Special variables holding references to external resources.

  2. User-defined Variables:

    • Created by the programmer to store data as needed.
    $userDefinedVariable = "I am user-defined";

These are the primary categories of PHP variables based on scope, data type, and origin. Understanding these categories helps in organizing and managing variables within PHP scripts.




Predefined/Superglobal Variables

In PHP, predefined variables are global variables that are always accessible, regardless of the scope of the script. These variables are automatically populated by the PHP interpreter, and they provide information about the environment, server, and user. Here are some categories of predefined variables in PHP:

  1. Superglobals:

    • $_GLOBALS: Contains all global variables.

    • $_SERVER: Contains information about the server and execution environment.

    • $_REQUEST: Contains data sent to the script via HTTP request methods (GET, POST, etc.).

    • $_POST: Contains data sent to the script using HTTP POST method.

    • $_GET: Contains data sent to the script using HTTP GET method.

    • $_FILES: Contains information about file uploads via HTTP POST.

    • $_ENV: Contains environment variables.

    • $_COOKIE: Contains data sent to the script via HTTP cookies.

    • $_SESSION: Contains session variables.

  2. Server Information:

    • $_SERVER['PHP_SELF']: The filename of the currently executing script.

    • $_SERVER['SERVER_NAME']: The name of the server host.

    • $_SERVER['REQUEST_METHOD']: The request method used to access the page (e.g., "GET", "POST").

    • $_SERVER['HTTP_USER_AGENT']: The user agent string of the browser.

    • $_SERVER['REMOTE_ADDR']: The IP address of the user making the request.

  3. File Uploads:

    • $_FILES['file']['name']: The original name of the uploaded file.

    • $_FILES['file']['type']: The MIME type of the uploaded file.

    • $_FILES['file']['size']: The size, in bytes, of the uploaded file.

    • $_FILES['file']['tmp_name']: The temporary filename of the file in which the uploaded file was stored on the server.

  4. Session Handling:

    • $_SESSION['variable']: Access session variables.
  5. Client-Side Information:

    • $_GET['variable']: Access variables passed to the script via URL parameters.

    • $_POST['variable']: Access variables passed to the script via POST method.

  6. Environment Variables:

    • $_ENV['variable']: Access environment variables.
  7. Error Handling:

    • $_REQUEST['variable']: Contains data sent to the script via any HTTP request method.

    • $_COOKIE['variable']: Access variables sent to the script via HTTP cookies.

These predefined variables play a crucial role in handling input, managing sessions, and obtaining information about the server and execution environment in PHP scripts.


Let's provide examples for each topic:

1. Superglobals:

// $_GLOBALS
$globalVariable = "I am a global variable.";

function exampleFunction() {
    echo $GLOBALS['globalVariable'];
}

exampleFunction();

// $_SERVER
echo $_SERVER['PHP_SELF']; // The filename of the currently executing script.

// $_REQUEST, $_POST, $_GET
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $postData = $_POST['data']; // Access data sent via POST
} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $getData = $_GET['data']; // Access data sent via GET
}

// $_FILES
$fileUploadName = $_FILES['file']['name'];

// $_ENV
$envVariable = $_ENV['PATH'];

// $_COOKIE
$cookieValue = $_COOKIE['username'];

// $_SESSION
session_start();
$_SESSION['user_id'] = 123;

2. Server Information:

// $_SERVER
echo $_SERVER['SERVER_NAME']; // The name of the server host.
echo $_SERVER['REQUEST_METHOD']; // The request method used to access the page.
echo $_SERVER['HTTP_USER_AGENT']; // The user agent string of the browser.
echo $_SERVER['REMOTE_ADDR']; // The IP address of the user making the request.

3. File Uploads:

// $_FILES
$uploadedFileName = $_FILES['file']['name'];
$uploadedFileType = $_FILES['file']['type'];
$uploadedFileSize = $_FILES['file']['size'];
$uploadedFileTmpName = $_FILES['file']['tmp_name'];

4. Session Handling:

// $_SESSION
session_start();
$_SESSION['user_id'] = 123;

// Access session variable
echo $_SESSION['user_id'];

5. Client-Side Information:

// $_GET
$variableFromGet = $_GET['variable'];

// $_POST
$variableFromPost = $_POST['variable'];

6. Environment Variables:

// $_ENV
$envVariable = $_ENV['PATH'];

7. Error Handling:

// $_REQUEST
$requestData = $_REQUEST['data'];

// $_COOKIE
$cookieValue = $_COOKIE['username'];

These examples demonstrate how to use predefined variables in various scenarios within PHP scripts.


Data Type-based Categories:

In PHP, variables can have various data types. Here are the main data types and categories:

1. Scalar Types:

  • Integer:

      $intVar = 42;
    
  • Float (Double):

      $floatVar = 3.14;
    
  • String:

      $stringVar = "Hello, World!";
    
  • Boolean:

      $boolVar = true;
    

2. Compound Types:

  • Array:

      $arrayVar = [1, 2, 3, 'apple', 'orange'];
    
  • Object:

      class MyClass {
          public $property = 'value';
      }
    
      $objectVar = new MyClass();
    
  • Callable:

      function myFunction() {
          echo "Hello!";
      }
    
      $callableVar = 'myFunction';
      $callableVar();  // Calls the function
    

3. Special Types:

  • Resource: (Used to represent resources, like database connections.)

      $file = fopen('example.txt', 'r');
    
  • Null:

      $nullVar = null;
    

4. Pseudo-Types:

  • Mixed: (Represents multiple possible types.)

      function exampleFunction(mixed $param) {
          // Code
      }
    
  • Number: (Represents either an integer or a float.)

      function addNumbers(number $a, number $b): number {
          return $a + $b;
      }
    

5. Compound Types (Arrays):

  • Indexed Array:

      $indexedArray = [1, 2, 3];
    
  • Associative Array:

      $assocArray = ['name' => 'John', 'age' => 30];
    
  • Multidimensional Array:

      $multiArray = [
          [1, 2, 3],
          ['a', 'b', 'c'],
      ];
    

6. Variable Variables:

(Using the value of a variable as the name of another variable.)

$variableName = 'dynamicVar';
$$variableName = "I am a dynamic variable.";
echo $dynamicVar;

7. Constants:

(Identifiers that represent simple values, not variables.)

define("PI", 3.14);
echo PI;

8. Type Juggling and Type Casting:

  • Type Juggling:

      $intVar = 42;
      $stringVar = "The answer is: " . $intVar;
    
  • Type Casting:

      $floatVar = 3.14;
      $intVar = (int)$floatVar;
    

These are the primary data types and categories in PHP, each serving specific purposes in programming. Keep in mind that PHP is dynamically typed, meaning you don't need to declare the data type of a variable explicitly. The type is determined at runtime based on the value assigned to the variable.


Did you find this article valuable?

Support Saifur's Blog by becoming a sponsor. Any amount is appreciated!