Basic Syntax
Overview
Understanding PHP's syntax is essential for writing clean, readable, and maintainable code. This chapter covers the fundamental syntax rules, conventions, and best practices that every PHP developer should know.
PHP Opening and Closing Tags
Standard PHP Tags
Mixing HTML and PHP
Short Echo Tags (PHP 5.4+)
Important Notes
- Always use
<?phptags (avoid short tags<?) - The closing
?>tag is optional at the end of PHP-only files - No whitespace before opening tag in PHP-only files
Statements and Expressions
Statements
Every PHP statement must end with a semicolon:
Expressions
Expressions evaluate to a value:
Case Sensitivity Rules
Case-Sensitive Elements
Case-Insensitive Elements
Comments
Single-Line Comments
Multi-Line Comments
Documentation Comments (PHPDoc)
Variables
Variable Declaration and Naming
Variable Variables
Variable Scope
Constants
Defining Constants
Magic Constants
Class Constants
Operators
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Increment/Decrement Operators
String Operators
Control Structures Syntax
If-Else Statements
Alternative Syntax
String Syntax
Single vs Double Quotes
Heredoc Syntax
Nowdoc Syntax (PHP 5.3+)
Array Syntax
Array Declaration
Function Syntax
Function Declaration
Coding Standards and Best Practices
PSR-1 Basic Coding Standard
Naming Conventions
Code Formatting
Error Handling Syntax
Try-Catch Blocks
Next Steps
Now that you understand PHP's basic syntax, let's explore how PHP programs are structured in Program Structure.
Practice Exercises
- Create variables using different naming conventions and test case sensitivity
- Write a script using all types of operators
- Practice string interpolation with single quotes, double quotes, and heredoc
- Create functions with different parameter types and return values
- Write code following PSR-1 standards
Understanding these syntax fundamentals will make the rest of your PHP journey much smoother!