In any programming language, understanding basic syntax, variables, and constants is foundational. PHP is no exception. This lesson delves into these core concepts.
Basic PHP Syntax
PHP's syntax is akin to that of the C language, offering familiarity to those experienced with C.
- Embedding PHP in Files: PHP code can be placed anywhere within a
.php
file. - PHP Tags: Code blocks start with
<?php
and end with?>
. While short tags<?
are available, their use is discouraged. - Pure PHP Files: If a file contains only PHP code, it's advisable to omit the closing
?>
tag to prevent unintended whitespace or new lines after the closing tag. - Statement Termination: Each PHP statement should end with a semicolon
;
.
Example:
Comments in PHP
Comments are non-executable parts of the code, serving to explain and document. They assist in code maintenance and clarity.
- Single-line Comments:
// This is a single-line comment
# This is also a single-line comment
- Multi-line Comments:
/* This is a multi-line comment spanning multiple lines */
Declaring Variables in PHP
Variables are used to store data and are prefixed with the $
symbol.
- Naming Rules:
- Must start with a letter or underscore (
_
). - Can contain letters, numbers, and underscores.
- Case-sensitive (
$Variable
and$variable
are distinct).
- Must start with a letter or underscore (
Example:
Variable Scope
The scope determines where a variable can be accessed.
- Global Scope: Variables declared outside functions.
- Local Scope: Variables declared within functions.
- Superglobals: Built-in variables accessible everywhere (e.g.,
$_GET
,$_POST
).
Dynamic Variable Names
PHP allows dynamic variable naming using variable variables.
Example:
Declaring Constants in PHP
Constants are immutable values defined using the define()
function or the const
keyword (PHP 5.3+).
- Naming Rules:
- By convention, constants are uppercase.
- Must start with a letter or underscore.
- Can contain letters, numbers, and underscores.
Example:
Magic Constants
PHP provides predefined constants that change based on their context.
__LINE__
: Current line number.__FILE__
: Full path and filename.__DIR__
: Directory of the file.__FUNCTION__
: Function name.__CLASS__
: Class name.__METHOD__
: Class method name.__NAMESPACE__
: Current namespace.
Understanding these fundamentals is crucial for effective PHP programming. They form the building blocks upon which more complex concepts are built.