2. Writing Your First PHP Script.

Before we dive into writing our first PHP script, let’s set up our project directory.

Setting Up Your Project Directory:

  1. Finding the Root Directory:
    • Windows: If you’re using XAMPP or WAMP on Windows, the root directory is typically located within the installation folder of your XAMPP or WAMP software. By default, it’s often located in C:\xampp\ or C:\wamp\.
    • macOS: For macOS users using MAMP, the root directory is usually located within the MAMP application folder. You can find it by navigating to /Applications/MAMP/.
    • Linux: On Linux systems, the root directory for XAMPP or WAMP installations can vary depending on your setup. Typically, it’s located within the installation directory, such as /opt/lampp/ for XAMPP.
  2. Creating the Project Directory:
    • Once you’ve located the root directory of your XAMPP, WAMP, or MAMP installation, open the directory.
    • Navigate to the www directory, and create a new folder named php-basics.

PHP rules, syntax rules, and conventions

  1. Opening and Closing Tags:
    • PHP code is enclosed within <?php and ?> tags.
    • Short tags (<? and ?>) are discouraged due to compatibility issues and may be disabled in some PHP configurations.
  2. Comments:
    • Single-line comments start with // or #.
    • Multi-line comments are enclosed between /* and */.
  3. Statements:
    • PHP statements end with a semicolon (;).
  4. Whitespace:
    • Whitespace (spaces, tabs, newlines) is generally ignored in PHP.
    • However, proper indentation is recommended for readability.
  5. Case Sensitivity:
    • PHP is case-sensitive for variable names, function names, and constants.
    • For example, $variable and $Variable are considered different variables.
  6. Variables:
    • Variables in PHP start with a dollar sign ($) followed by the variable name.
    • Variable names must start with a letter or underscore, followed by letters, numbers, or underscores.
    • Variable names cannot start with a number.
  7. Data Types:
    • PHP supports various data types including strings, integers, floats, booleans, arrays, and objects.
    • Data types are loosely typed, meaning you don’t need to declare the data type when creating a variable.
  8. Constants:
    • Constants are defined using the define() function.
    • Constant names are conventionally written in uppercase letters with underscores separating words.
  9. Operators:
    • PHP supports arithmetic, assignment, comparison, logical, and other types of operators.
  10. Strings:
    • Strings can be enclosed in single (') or double (") quotes.
    • Variable interpolation (replacing variables within strings) is only supported in double-quoted strings.
  11. Control Structures:
    • PHP supports various control structures including if-else statements, loops (for, while, do-while, foreach), and switch statements.
  12. Functions:
    • Functions are defined using the function keyword followed by the function name and parameters.
    • Function names are not case-sensitive.
  13. Include and Require:
    • PHP includes external files using include, include_once, require, or require_once statements.
  14. Error Handling:
    • PHP provides mechanisms for error reporting and handling including try-catch blocks for exceptions.
  15. Coding Conventions:
    • Following coding conventions improves code readability and maintainability.
    • Conventions for variables, constants, function names, and indentation should be followed consistently.

Adhering to these rules, syntax rules, and conventions helps ensure consistency, readability, and maintainability in PHP codebases.

Creating Your First PHP Script:

  1. Creating the PHP File:
    • Now that we have our project directory set up, let’s create our first PHP script file. Inside the php-basics folder, create a new text file.
    • Rename the text file to helloworld.php.
  2. Opening the PHP File:
    • Open the helloworld.php file in a text editor or IDE of your choice. This is where we’ll write our PHP code.

The “Hello, World!” tradition.

The “Hello, World!” tradition in coding is a time-honored tradition that serves as the very first program many developers write when learning a new programming language or environment. Despite its simplicity, the “Hello, World!” program holds significant importance for several reasons:

Introduction to Syntax: Writing a “Hello, World!” program introduces beginners to the basic syntax and structure of a programming language. It provides a straightforward example of how to output text to the screen or other output mediums.

Verification of Setup: Running a “Hello, World!” program allows developers to verify that their development environment is correctly set up and functioning as expected. It confirms that the programming language is installed and configured correctly.

Building Confidence: For novice programmers, seeing their first program execute successfully and display the expected output can be a confidence booster. It marks the beginning of their journey into the world of coding and shows that they can write functional code.

Standardized Comparison: Since the “Hello, World!” program is so widely used across different programming languages and environments, it provides a standardized basis for comparing and contrasting the syntax and structure of various languages.

Cultural Significance: The “Hello, World!” tradition has become a cultural phenomenon within the coding community, serving as a shared experience and point of connection for developers worldwide. It’s often seen as a rite of passage for beginners.

Overall, while the “Hello, World!” program may seem simple, its significance lies in its role as a foundational step in the learning process and as a symbol of initiation into the world of programming.

Your First PHP Script:

Now, let’s write a simple “Hello, World!” PHP script to test our setup:

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

Now, let’s explain each line:

  1. <?php – This is called the PHP opening tag. It indicates the beginning of a PHP script. When the PHP interpreter encounters this tag, it knows that the following code contains PHP instructions.
  2. echo "Hello, World!"; – This line is where the actual work is done. Here’s what each part does:
    • echo – echo is a PHP construct used to output data. It takes the string “Hello, World!” enclosed in double quotes and displays it on the screen.
    • "Hello, World!" – This is the text that will be displayed on the screen. In this case, it’s the classic “Hello, World!” message.
  3. ?> – This is the PHP closing tag. It indicates the end of the PHP script. Everything after this tag is treated as HTML or other content outside of PHP. In this simple script, it’s not strictly necessary, but it’s good practice to include it to clearly mark the end of the PHP code.

So, when you put it all together, this PHP script does one thing: it outputs the message “Hello, World!” to the screen. It’s a basic demonstration of how to use the echo construct to display text in a PHP script.

Testing Your PHP Script:

  1. Save the helloworld.php file.
  2. Open your web browser.
  3. Navigate to http://localhost/php-basics/helloworld.php (adjust the URL based on your project directory name if different).

You should see “Hello, World!” displayed in your web browser. Congratulations! You’ve successfully written and executed your first PHP script.

PHP terms and concepts

Here are some fundamental PHP terms and concepts that beginners should be familiar with:

  1. Variable: A named container for storing data values. Variables in PHP start with a dollar sign ($) followed by the variable name.
  2. Data Types:
    • String: A sequence of characters enclosed in single or double quotes.
    • Integer: Whole numbers without decimal points.
    • Float (Double): Numbers with decimal points.
    • Boolean: Represents true or false values.
    • Array: A collection of key-value pairs or indexed values.
    • Object: An instance of a class containing properties and methods.
  3. Operators: Symbols or keywords that perform operations on variables and values. Includes arithmetic operators, assignment operators, comparison operators, and logical operators.
  4. Conditional Statements: Control structures that execute different blocks of code based on specified conditions. Includes if, else, elseif, and the ternary operator (? :).
  5. Loops: Control structures that repeat a block of code multiple times. Includes for, while, do-while, and foreach.
  6. Function: A block of reusable code that performs a specific task. Functions help organize code and make it more modular.
  7. Constructs: Special language elements or syntax provided by PHP.
    • Echo and Print: Constructs for outputting data to the browser.
    • Include and Require: Constructs for including external PHP files within a script.
    • Array() Constructor: Constructs for creating arrays.
  8. String Manipulation: Operations performed on strings, such as concatenation, substring extraction, string length, and searching within strings.
  9. Superglobals: Predefined variables in PHP that are accessible from any scope within a script. Examples include $_GET, $_POST, $_SESSION, $_COOKIE, and $_SERVER.
  10. Constants: Variables whose values cannot be changed once defined. Constants are defined using the define() function and are case-sensitive by default.
  11. Comments: Annotations within the code that are ignored by the PHP interpreter. Comments help document code and improve readability.
  12. Control Structures: Constructs that dictate the flow of execution within a PHP script. Includes loops, conditional statements, and switch statements.
  13. Error Handling: Techniques for identifying, reporting, and handling errors in PHP code. This includes using try, catch, and finally blocks for exception handling.
  14. Scope: The visibility of variables within different parts of a PHP script. PHP supports global scope, local scope, static scope, and class scope.
  15. Object-Oriented Programming (OOP) Concepts: Fundamental principles of OOP, such as classes, objects, inheritance, encapsulation, and polymorphism.

Understanding these terms and concepts is crucial for building a strong foundation in PHP programming and transitioning to more advanced topics and techniques. Most of these terms will be explored deeper in further topics.