ⓅThe Complete PHP Guide: Symbols, Syntax, and Inner Workings
Welcome to the ultimate, all-encompassing guide to PHP. Whether you are a complete beginner or a seasoned developer looking for a refresher, this guide covers everything—from its core definition to the tiniest symbolic operators.
---
1. TITLE: What is PHP?
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used, open-source, server-side scripting language designed primarily for web development.
· Creator: Rasmus Lerdorf (1994).
· Current Stable Version: PHP 8.x (JIT compilation included).
· Paradigm: Procedural, Object-Oriented, and Functional.
· Execution: Embedded directly within HTML code and executed on the web server, generating dynamic web content.
---
2. HOW DOES PHP WORK? (The Lifecycle)
PHP is a server-side language, meaning the code is executed on the host server, not the user's browser. Here is the step-by-step flow:
2. Server Dispatch: The web server (Apache/Nginx) recognizes the .php extension and passes the file to the PHP Interpreter (the Zend Engine).
3. Parsing & Compilation: The interpreter reads the raw PHP code, parses it into an Abstract Syntax Tree (AST), and compiles it into Zend Opcodes (bytecode).
4. Execution: The Zend VM (Virtual Machine) executes these opcodes. If the code connects to a database (like MySQL), it fetches the data.
5. Output Generation: The PHP engine generates pure HTML (and/or JSON, XML, images) based on the logic.
6. Response: The server sends this generated HTML back to the client's browser. The user never sees the PHP source code—only the output.
PHP 8+ Modern Efficiency: PHP 8 uses a JIT (Just-In-Time) compiler, which optimizes CPU-intensive tasks by compiling hotspots of the opcodes into machine code at runtime, making mathematical and algorithmic tasks significantly faster.
---
3. BASIC SYNTAX & STRUCTURE
3.1. Standard Tags (Escaping from HTML)
PHP code must be wrapped in specific tags to tell the engine where to execute.
Tag Description Usage
<?php ... ?> Standard/XML Style (Recommended) <?php echo "Hello"; ?>
<?= ... ?> Short Echo Tag (Always enabled in PHP 8) <?= $variable ?>
<? ... ?> Short Open Tag (Deprecated/Disabled by default) Avoid using.
<script language="php"> ... </script> Obsolete HTML style Not recommended.
```php
<!DOCTYPE html>
<html>
<body>
<?php echo "This is PHP executed inside HTML!"; ?>
<?= "This is a shorter way to echo." ?>
</body>
</html>
```
3.2. Comments
```php
// This is a single-line comment (C++ style)
# This is also a single-line comment (Unix style)
/* This is a
multi-line
comment (C style) */
```
· Variables are case-sensitive ($name ≠ Name).
· Keywords (like if, echo, while) are not case-sensitive.
· Class names/Methods/Functions are mostly case-insensitive but highly recommended to use exact casing.
---
4. THE COMPLETE SYMBOLS AND OPERATORS REFERENCE
This is the core of your request. Let's break down every single symbol used in PHP.
4.1. The "Dollar Sign" ($) - Variable Identifier
The $ symbol is the prefix for all variables in PHP.
```php
$name = "John"; // Correct
name = "John"; // Error! Missing $
```
4.2. Arithmetic Operators (Math)
Used to perform mathematical operations.
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 3 3.333... (float)
% Modulus (Remainder) 10 % 3 1
** Exponentiation (PHP 5.6+) 2 ** 3 8 (2 to the power of 3)
4.3. Assignment Operators
"
4.4. Comparison Operators (Return bool)
Used to compare two values.
Symbol Name Example Result
== Equal (value only) 5 == "5" true (types are ignored)
=== Identical (value AND type) 5 === "5" false (int vs string)
!= / <> Not Equal 5 != 4 true
!== Not Identical 5 !== "5" true
<= Less than or equal 3 <= 3 true
>= Greater than or equal 3 >= 5 false
<=> Spaceship Operator (PHP 7+) 3 <=> 5 Returns -1 (less), 0 (equal), or 1 (greater).
?? Null Coalescing (PHP 7+) $name ?? "Guest" Returns $name if exists and not null; else returns "Guest".
?: Ternary Shortcut $x ?: "default" Returns $x if true, else "default".
4.5. Logical Operators (Work with booleans)
Symbol Name Example Result
&& / and And true && false false
\|\| / or Or true \|\| false true
! Not (Negation) !true false
xor Exclusive Or true xor true false (one must be true, not both)
Note: && has higher precedence than and. Use && and || for standard logic.
4.6. Increment / Decrement Operators (Change values by 1)
Symbol Name Example Description
++$x Pre-increment $y = ++$x Increments $x by 1, then assigns to $y.
$x++ Post-increment $y = $x++ Assigns $x to $y, then increments $x.
--$x Pre-decrement $y = --$x Decrements $x by 1, then assigns.
$x-- Post-decrement $y = $x-- Assigns $x, then decrements.
4.7. String Operators (Working with text)
Symbol Name Example Result
. Concatenation "Hello " . "World" "Hello World"
.= Concatenation Assign $a = "Hi"; $a .= " John"; $a becomes "Hi John"
4.8. Array Operators (Comparing and combining)
Symbol Name Example Result
+ Union $a + $b Merges arrays (keeps left-side if keys collide).
== Equality $a == $b true if key/value pairs are identical.
=== Identity $a === $b true if identical and in the same order/type.
!= / <> Inequality $a != $b Returns true if not equal.
!== Non-identity $a !== $b Returns true if not identical.
4.9. Special Symbols (Crucial for advanced PHP)
Symbol Name Usage
& Reference (Pointer) Creates a reference to a variable, not a copy. $a = &$b; (Both point to same memory). Also used in Call by Reference: function test(&$var).
-> Object Operator Used to access properties/methods of an instantiated class. $obj->method();
:: Scope Resolution (Paamayim Nekudotayim) Used to access static methods, constants, or parent class properties. ParentClass::CONSTANT;
\ Namespace Separator Used to denote namespaces. use \DateTime; or $obj = new \MyNamespace\MyClass();
@ Error Control Operator Suppresses error messages for a single expression. @file_get_contents('file.txt'); (USE SPARINGLY—bad practice).
... Spread Operator / Splat (PHP 5.6+) Used in function definitions to capture variable arguments, or in arrays to unpack: function sum(...$numbers) {} or $array = [...$oldArray]; (PHP 7.4+).
$ inside strings Variable Interpolation In double-quoted strings (" ") and Heredoc, variables are expanded. echo "Hello $name";
{} Curly Braces / Complex Syntax Isolate variable names in strings: echo "Hello {$name}s"; Also used for defining classes (class MyClass {}) and control structures (if(1){ ... }).
[] Square Brackets Define arrays: $arr = [1, 2, 3]; or access indexes: $arr[0].
() Parentheses Enclose function calls, control expressions (if, while), and override mathematical precedence ((2+3)*4).
---
5. DATA TYPES IN PHP (Dynamic Types)
PHP is a loosely-typed language (types are determined at runtime).
· Scalar Types: int, float, string, bool.
· Compound Types: array, object, callable, iterable.
Type Declarations (PHP 8+): You can now enforce types strictly.
```php
declare(strict_types=1); // Enables strict typing
function add(int $a, int $b): int {
return $a + $b;
}
```
---
6. VARIABLES & SCOPE
· Global Scope: Variables defined outside functions. To use inside, use the global keyword or $GLOBALS superglobal.
· Local Scope: Variables defined inside a function.
· Static Scope: Use static $count = 0; inside a function to keep the value between calls.
PHP Superglobals (Accessible everywhere):
· $_GET - Data from URL parameters.
· $_POST - Data from HTTP POST forms.
· $_SESSION - Session data.
· $_COOKIE - Cookie data.
· $_SERVER - Server/environment info.
· $_FILES - File uploads.
· $_REQUEST - Contains $_GET, $_POST, $_COOKIE.
---
7. CONTROL STRUCTURES (Logic)
Conditionals:
```php
// If/Else
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
// Switch/Case
switch ($color) {
case 'red':
echo "Stop";
break;
case 'green':
echo "Go";
break;
default:
echo "Wait";
}
```
Loops:
// While
while ($i <= 5) { echo $i++; }
// Do-While
do { echo $i++; } while ($i <= 5);
// For
for ($i=0; $i<10; $i++) { echo $i; }
// Foreach (Best for arrays)
foreach ($array as $key => $value) {
echo "Key: $key, Value: $value";
}
```
---
· Defining: function myFunc($param) { return $param * 2; }
· Including Files:
· include (Generates a warning if fails).
· require (Generates a fatal error if fails).
· include_once / require_once (Ensures file is included only once).
---
9. OBJECT-ORIENTED PROGRAMMING (OOP) SUMMARY
PHP supports full OOP. Key symbols remain the same, but here are the keywords:
```php
class Vehicle {
public $wheels; // Public property
protected $engine; // Accessed by child classes only
private $vin; // Accessed only inside this class
public function __construct($wheels) { // Constructor
$this->wheels = $wheels; // $this refers to current object
}
public function drive(): string {
return "Driving with $this->wheels wheels!";
}
}
// Inheritance
class Car extends Vehicle {
public function drive(): string {
return parent::drive() . " Vroom!"; // Override
}
}
```
---
10. PHP 8+ "NEW" SYMBOLS & FEATURES (Must Know)
1. match Expression (New Ternary Alternative):
```php
$result = match($status) {
200, 201 => "Success",
404 => "Not Found",
default => "Unknown"
};
2. ?-> (Nullsafe Operator):
If the object is null, it returns null instead of throwing an error.
```php
$city = $user?->getProfile()?->getAddress()?->city;
```
3. Attributes (#[...]): Replaces docblock annotations.
```php
#[Route('/api/posts', methods: ['GET'])]
function getPosts() {}
```
---
11. PROS & CONS OF PHP
Pros Cons
Extremely easy to learn (low barrier to entry). Historical inconsistent function naming (strpos vs str_split).
Massive community and vast ecosystem (Composer). Slower than compiled languages like Go or Rust (though PHP 8+ JIT helps).
Scales massively (Facebook, Wikipedia, Slack). Async programming is less intuitive than Node.js (though Swoole/ReactPHP exist).
77%+ of the web uses PHP (WordPress, Laravel, Symfony). Shared-nothing architecture can be heavy for real-time apps without extra services.
12. CONCLUSION: THE BOTTOM LINE
PHP is the undisputed king of the back-end web, powering nearly 8 out of 10 websites. Understanding the symbols—from the simple $ to the advanced ?? and <=>—gives you absolute control over the language's logic. By leveraging modern PHP (8.0+) with strict typing and object-oriented principles, you can build anything from a simple contact form to an enterprise-grade SaaS platform.
Your first step today: Open a .php file, type <?php echo "Hello World!"; ?>, run it on a local server (like XAMPP or Laravel Valet), and watch the magic of server-side scripting come to life.
Comments
Post a Comment
Thanks for sharing your thoughts! Stay tuned for more updates