Tag Archives: variable variables

Learning PHP The Right Way vol 2

Notes for myself from youtube tutorial Full PHP 8 Tutorial - Learn PHP The Right Way by Program With Gio. Video nr 4: What Are Constants & Variable Variables In PHP - Full PHP 8 Tutorial
  1. Constants - we can't overwrite values. Constants are defined using uppercase. There are two ways of defining constants:
    • define('name', 'value');
      <?php define ('STATUS_PASSED', 1);
      echo SATUS_PASSED
      ?>
      
      or
      <?php 
      $passed = 1;
      define('STATUS_'.$passed, 1);
      echo STATUS_PAID
      ?>
      returns
      1
      This function is defined at a runtime and can be used in control structures - if true then define('HEALTH', 'ok').
    • const
      <?php
          const STATUS_PASSED=1;
          echo STATUS_PASSED
      ?>
      It is defined during compile time, it means can't use it in loops and if /else.
  2. To find out if the constant is defined, we can use:
    <?php
        echo defined('STATUS_PASSED')
        ?>
    It returns boolean. If it returns 1, the constant is defined.
  3. Magical constants are this:
    <?php   
    echo __LINE__ (two underscores);
    ?>
    Their value depends where they are used.
  4. Variable variables $$a- takes the variable's value and treats it as the name of the new variable.
    <?php  
    $a = "capital";
    $$a
     = "city";
    echo $a.$capital  //returns "capitalcity"
    ?>
    Variable variables can be also printed out like this:
    <?php
    echo $a.$a;
    echo "$a.{$a}";
    echo "$a.${$a}"
    ?>