PHP Syntax: Tags, Comments, Variables, and Constants

When starting with PHP, it’s important to understand its basic syntax. This is the foundation of every PHP project you’ll build.

1. PHP Tags

PHP code must be written inside special tags so the server can identify it.

Example:
<?php
    echo "Hello, World!";
?>

πŸ‘‰ Explanation:

  • <?php ... ?> β†’ The standard PHP tag.
  • Inside, you can write any PHP code.
  • echo is used to output text to the browser.

2. PHP Comments

Comments are ignored by the PHP engine but help developers understand the code.

Example:
<?php
    // Single-line comment

    # Another single-line comment

    /*
      Multi-line comment
      This can span multiple lines
    */
?>

πŸ‘‰ Explanation:

  • // β†’ Single-line comment.
  • # β†’ Another way to write single-line comments.
  • /* ... */ β†’ Multi-line comments.

3. PHP Variables

Variables are used to store data. They always start with a $ sign.

Example:
<?php
    $name = "John";      // String
    $age = 25;           // Integer
    $is_student = true;  // Boolean

    echo "My name is $name and I am $age years old.";
?>

πŸ‘‰ Explanation:

  • $name, $age, $is_student are variables.
  • Variables can store different data types like strings, integers, booleans, etc.
  • Output will be: My name is John and I am 25 years old.

4. PHP Constants

Constants are like variables, but their value cannot be changed once defined.

Example:
<?php
    // Defining a constant
    define("SITE_NAME", "My PHP Blog");

    // Using the constant
    echo "Welcome to " . SITE_NAME;

    // Trying to change value (Not allowed)
    // SITE_NAME = "Another Blog"; ❌ Error
?>

πŸ‘‰ Explanation:

  • define("SITE_NAME", "My PHP Blog") β†’ Creates a constant.
  • Constants don’t use $ sign.
  • They are useful for values that should not change (like site name, API keys).

βœ… Now you know the basics of PHP syntax: tags, comments, variables, and constants.

PHP Tutorial