PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language primarily designed for web development. It powers millions of websites, including WordPress, Facebook, and Wikipedia. This article dives deep into PHP, covering everything from architecture to syntax, internals, and key features.
1. PHP Architecture
PHP has a modular and layered architecture designed for flexibility, efficiency, and ease of embedding within HTML.
Key Components:
- Zend Engine The core of PHP, responsible for parsing and executing PHP code. It includes:
- Lexer: Converts PHP code into tokens.
- Parser: Converts tokens into an Abstract Syntax Tree (AST).
- Compiler: Translates AST to opcodes.
- Executor: Runs opcodes to produce output.
- PHP SAPI (Server API) PHP can run in different environments through SAPIs:
-
Apache Module (
mod_php): Embedded in Apache. - CGI / FastCGI: Interface for web servers.
- CLI (Command Line Interface): Run PHP scripts from the terminal.
- Extensions and Libraries PHP is extendable using C-based extensions:
- MySQL, PostgreSQL, SQLite, MongoDB
- cURL, GD (graphics), OpenSSL
- Custom extensions
- Configuration (php.ini) Central configuration file controlling PHP behavior:
- Error reporting
- Memory limits
- Upload size
- Extensions
Architecture Flow:
PHP Script → Lexer → Parser → AST → Compiler → Opcodes → Executor → Output
2. PHP Internals
Understanding PHP internals helps optimize performance and debug issues.
2.1 Memory Management
- PHP uses a reference counting mechanism for garbage collection.
- Memory is allocated for variables dynamically.
- Circular references are handled by a cyclic garbage collector.
2.2 Variable Handling
- Variables in PHP are loosely typed.
- Stored as
zvalstructures internally:
struct _zval_struct {
zend_value value;
zend_uint refcount__gc;
zend_uchar type;
zend_uchar is_ref__gc;
};
2.3 Execution Model
- PHP is interpreted, though Opcache can compile code to bytecode for performance.
- Each request starts a new execution environment.
3. PHP Syntax
PHP syntax is C-like and designed for easy embedding into HTML.
3.1 Basic Structure
<?php
// Single-line comment
# Another single-line comment
/*
Multi-line comment
*/
echo "Hello, World!";
?>
3.2 Variables
- Prefix with
$.
$name = "Klie";
$age = 25;
$price = 99.99;
$isActive = true;
3.3 Data Types
PHP supports scalar, compound, and special types.
| Type | Example |
|---|---|
| Integer | $i = 100; |
| Float | $f = 10.5; |
| Boolean | $b = true; |
| String | $s = "PHP"; |
| Array | $arr = [1,2,3]; |
| Object | $obj = new MyClass(); |
| NULL | $n = null; |
| Resource | $res = fopen("file.txt"); |
3.4 Operators
- Arithmetic:
+ - * / % ** - Assignment:
= += -= *= /= %= .= - Comparison:
== === != !== < > <= >= <=> - Logical:
&& || ! and or xor - String:
. .=
3.5 Control Structures
Conditional Statements
if ($age > 18) {
echo "Adult";
} elseif ($age > 12) {
echo "Teenager";
} else {
echo "Child";
}
Switch Statement
switch($color) {
case "red":
echo "Red color";
break;
case "blue":
echo "Blue color";
break;
default:
echo "Unknown color";
}
Loops
// while loop
$i = 0;
while ($i < 5) {
echo $i;
$i++;
}
// for loop
for ($i=0; $i<5; $i++) {
echo $i;
}
// foreach loop
$arr = [1,2,3];
foreach($arr as $value) {
echo $value;
}
3.6 Functions
function add($a, $b): int {
return $a + $b;
}
echo add(5, 10);
Variable functions
function hello() { echo "Hello!"; }
$func = "hello";
$func(); // Calls hello()
3.7 Classes and Objects
class Person {
public $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function greet() {
return "Hello, I'm " . $this->name;
}
}
$p = new Person("Klie", 25);
echo $p->greet();
Visibility Keywords
-
public,protected,private -
staticproperties and methods
Inheritance
class Employee extends Person {
public $salary;
}
Interfaces & Abstract Classes
interface Workable {
public function work();
}
abstract class Staff {
abstract public function report();
}
3.8 Namespaces
namespace MyApp\Utils;
class Helper {}
3.9 Traits
trait Logger {
public function log($msg) { echo $msg; }
}
class User { use Logger; }
3.10 Error Handling
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "Always executed";
}
3.11 File Handling
$file = fopen("test.txt", "w");
fwrite($file, "Hello PHP");
fclose($file);
3.12 Superglobals
-
$_GET,$_POST,$_REQUEST -
$_SESSION,$_COOKIE,$_FILES,$_SERVER
3.13 Regular Expressions
preg_match("/php/i", "PHP is great", $matches);
print_r($matches);
3.14 Advanced Features
- Anonymous functions & Closures
$sum = function($a, $b) { return $a + $b; };
echo $sum(5,10);
- Generators
function genNumbers() {
for ($i=0;$i<5;$i++) yield $i;
}
foreach(genNumbers() as $n) echo $n;
- Type Declarations
function greet(string $name): string {
return "Hello, $name";
}
- Error & Exception Handling
- Attributes (PHP 8+) for metadata
4. PHP Extensions
Popular extensions include:
| Extension | Purpose |
|---|---|
| PDO | Database abstraction |
| cURL | HTTP requests |
| GD | Image manipulation |
| OpenSSL | Encryption |
| mbstring | Multibyte string functions |
| JSON | JSON encode/decode |
5. PHP Best Practices
- Always use prepared statements for SQL.
- Enable strict typing (
declare(strict_types=1);). - Use namespaces to avoid collisions.
- Follow PSR standards (PSR-1, PSR-4).
- Keep error reporting enabled in development.
6. PHP Evolution
- PHP 1.0 (1995) – Personal Home Page tools
- PHP 3.0 (1997) – Standardized scripting language
- PHP 4.0 (2000) – Zend Engine 1
- PHP 5.0 (2004) – OOP support, PDO
- PHP 7.0 (2015) – Performance boost, scalar types
- PHP 8.0 (2020) – JIT compiler, attributes, union types
7. Conclusion
PHP is a versatile, mature, and continually evolving language. Understanding its architecture, internals, syntax, and features empowers developers to write efficient, secure, and maintainable web applications. With its massive ecosystem and modern features, PHP remains a top choice for web development today.
Top comments (0)