PHP Refresher

Syntax

  • In a php file, only the code between <?php and ?> is executed. Rest is simply ignored by php parser.
  • Avoid use of <?= which is short for <?php echo, at all cost.
  • At the end of a php script, its good practice to omit closing tag (?>). This avoids new line being sent to server.
  • Always terminate php expressions with a semicolon. However, if your expression is last in the script/file (that uses closing tag at the end), you can omit the semicolon. Note: if you remove closing tag at the end of file, you can’t omit the semicolon.
// Example 1: PHP script with closing tag at the end.
<?php

// php code

// you can remove semicolon
mysqli_close( $db )
?>

// Example 2: PHP script without closing tag at the end.
<?php

// php code 

// you can't remove semicolon
mysqli_close( $db ); // if you remove, its an error!

Variables

  • Define descriptive variable names e.g., $counter, $firstName, $arguments
  • Stick to one naming convention for variables, function names, class names, and so on. e.g., $first_name vs $firstName
  • Don’t use reserved keywords for variable names e.g., $this
  • It is a good practice to assign default values to variables. Otherwise their value will default to value of their type e.g., integer and float default to zero (0), boolean default to FALSE, string default to empty string, array default to empty array.

Static variables

  • It exists in only function scope and it doesn’t lose its value when program leaves the function scope.
  • you can’t assign dynamic expression to static variables e.g., function call.
  • Example:
function static_demo(){

    static $dynamic_val = sqrt(9); // error
    static $constant_expression = 3*4; // ok
    static $counter = 0;
    return ++$counter;
}
echo static_demo() . '<br />'; // 1
echo static_demo() . '<br />'; // 2
echo static_demo() . '<br />'; // 3
// if you don't use 'static' keyword, then o/p would be always 1.

Constants

  • Its a good practice to use UPPERCASE naming convention when defining CONSTANTs.
  • The scope of a CONSTANT is global. This means you can access the value anywhere in your script without worrying about where it’s defined.
  • Useful function:
    • define(): to define a CONSTANT. e.g., define( ‘PI’, 3.14159);
    • constant(): to retrieve CONSTANT’s value. e.g., $pi = constant(‘PI’);
    • get_defined_constants(): Retrieve associative array of all CONSTANTs (key=CONSTANT, value=value).
  • Some important magic CONSTANTs:
    • __FILE__ : current file path.
    • __DIR__ : current directory path.
    • __NAMESPACE__ : current namespace.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.