diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 00000000..2a7db6dd
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,20 @@
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[Makefile]
+indent_style = tab
+
+[*.{zig,c,cpp,h,php,json,yml,yaml,md}]
+indent_style = space
+indent_size = 4
+
+[*.{yml,yaml}]
+indent_size = 2
+
+[*.md]
+trim_trailing_whitespace = false
\ No newline at end of file
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..e1ffdcde
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,21 @@
+* text=auto
+
+*.zig text eol=lf
+*.c text eol=lf
+*.cpp text eol=lf
+*.h text eol=lf
+*.php text eol=lf
+*.sh text eol=lf
+*.yml text eol=lf
+*.yaml text eol=lf
+*.zon text eol=lf
+.gitignore text eol=lf
+.gitattributes text eol=lf
+.editorconfig text eol=lf
+Makefile text eol=lf
+audit text eol=lf
+php text eol=lf
+
+*.bin binary
+*.gz binary
+*.phar binary
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index ac6b5d72..41a5d7f3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,9 +1,26 @@
zig-out/
zig-cache/
.zig-cache/
-test_compress
-/*.md
-!README.md
-.handoff/
docs/book/
+
+# Local tooling
+.handoff/
.claude/
+.idea/
+.vscode/
+*.code-workspace
+
+# Local state
+.env
+.env.*
+!.env.example
+*.log
+*.tmp
+*.swp
+.DS_Store
+Thumbs.db
+
+# Generated dependencies and test artifacts
+**/vendor/
+**/.cache/
+test_compress
\ No newline at end of file
diff --git a/Makefile b/Makefile
index 31f2ad50..43b52ee5 100644
--- a/Makefile
+++ b/Makefile
@@ -1,60 +1,49 @@
PKG_CONFIG_PATH := /opt/homebrew/opt/mysql-client/lib/pkgconfig:/opt/homebrew/opt/libpq/lib/pkgconfig:/opt/homebrew/opt/openssl@3/lib/pkgconfig:/opt/homebrew/opt/curl/lib/pkgconfig:/opt/homebrew/opt/icu4c@77/lib/pkgconfig:/opt/homebrew/opt/icu4c/lib/pkgconfig:/opt/homebrew/opt/gmp/lib/pkgconfig:/opt/homebrew/opt/gd/lib/pkgconfig:/opt/homebrew/opt/libsodium/lib/pkgconfig:/opt/homebrew/opt/openldap/lib/pkgconfig:$(PKG_CONFIG_PATH)
export PKG_CONFIG_PATH
-.PHONY: build
-build: ## Build zphp (Debug; ~30x slower than release due to Zig's debug allocator stack-trace capture). use `make release` for benchmarking
+.PHONY: build release test compat pdo examples bench bench-macro laravel symfony all-tests check docs clean help
+build: ## Build the debug binary
zig build
-.PHONY: release
-release: ## Build zphp in ReleaseFast (no debug allocator overhead). prefer for any perf-sensitive run; for testing zphp's actual PHP-execution speed
+release: ## Build the optimized binary
zig build -Doptimize=ReleaseFast
-.PHONY: test
-test: ## Run zig unit tests
+test: ## Run Zig unit tests
zig build test
-.PHONY: compat
compat: build ## Run PHP compatibility tests (requires PHP 8.4)
./tests/run
-.PHONY: pdo
pdo: build ## Run PDO driver tests
./tests/pdo_test
-.PHONY: examples
examples: build ## Run example project tests (requires PHP 8.4)
./tests/examples_test
-.PHONY: bench
bench: ## Run runtime benchmarks (ReleaseFast)
zig build -Doptimize=ReleaseFast
./benchmarks/runtime/run
-.PHONY: bench-macro
bench-macro: ## Track real-app perf vs php (WordPress + Laravel harnesses, ReleaseFast)
zig build -Doptimize=ReleaseFast
./benchmarks/macro/run
-.PHONY: laravel
laravel: build ## Run Laravel compatibility tests (requires PHP 8.4 + composer)
./tests/laravel/run
-.PHONY: symfony
symfony: build ## Run Symfony component and serve compatibility tests (requires PHP 8.4 + composer)
./tests/symfony/run
./tests/symfony/serve_run
-.PHONY: all-tests
all-tests: test compat examples laravel ## Run all tests
-.PHONY: docs
+check: test compat examples ## Run the standard local verification suite
+
docs: ## Serve docs locally with live reload
mdbook serve docs
-.PHONY: clean
clean: ## Clean build artifacts
rm -rf zig-out .zig-cache
-.PHONY: help
help: ## Show help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(firstword $(MAKEFILE_LIST)) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[32m%-20s\033[0m %s\n", $$1, $$2}'
diff --git a/README.md b/README.md
index 9f8295ab..a56b30a5 100644
--- a/README.md
+++ b/README.md
@@ -1,32 +1,59 @@
# zphp
-zphp is a PHP runtime written in Zig with PHP 8.x compatibility. It includes a built-in HTTP server with WebSocket support, TLS, and HTTP/2, database drivers for SQLite, MySQL, and PostgreSQL, and cURL bindings for HTTP client operations.
+**A high-performance PHP runtime built in Zig.**
+
+zphp is an experimental PHP 8.x-compatible runtime focused on **speed, low memory usage, and modern deployment**. It combines a custom runtime with a built-in HTTP server, WebSocket support, TLS, HTTP/2, database drivers, cURL bindings, package management, testing, formatting, and standalone compilation.
+
+Built with **Zig**, zphp is designed to give PHP workloads lower-level control, reduced overhead, and a more performance-oriented runtime architecture.
```sh
-zphp run app.php # run a script
-zphp serve app.php --port 8080 # start an HTTP server
-zphp build --compile app.php # compile to a standalone executable
-zphp test # run tests
-zphp fmt src/*.php # format code
-zphp install # install packages from composer.json
+zphp run app.php
+zphp serve app.php --port 8080
+zphp build --compile app.php
+zphp test
+zphp fmt src/*.php
+zphp install
```
-## Quick comparison
-
-| | PHP | zphp |
-|---|---|---|
-| Run a script | `php script.php` | `zphp run script.php` |
-| HTTP server | php-fpm + nginx | `zphp serve app.php` |
-| Install deps | `composer install` | `zphp install` |
-| Add a package | `composer require pkg` | `zphp add pkg` |
-| Run tests | `phpunit` | `zphp test` |
-| Format code | `php-cs-fixer fix` | `zphp fmt` |
-| Standalone binary | - | `zphp build --compile app.php` |
+## Features
+
+* PHP 8.x compatibility
+* Runtime written in Zig
+* Built-in HTTP server
+* HTTP/2, TLS, and WebSockets
+* SQLite, MySQL, and PostgreSQL
+* cURL bindings
+* Composer package support
+* Standalone executable compilation
+* Performance and low-memory focused architecture
+
+## Comparison
+
+| Task | PHP | zphp |
+| ----------------- | ------------------ | ---------------------- |
+| Run script | `php app.php` | `zphp run app.php` |
+| HTTP server | PHP-FPM + nginx | `zphp serve app.php` |
+| Dependencies | `composer install` | `zphp install` |
+| Tests | PHPUnit | `zphp test` |
+| Formatting | PHP-CS-Fixer | `zphp fmt` |
+| Standalone binary | External tooling | `zphp build --compile` |
## Installation
-Download prebuilt binaries from [GitHub Releases](https://github.com/nvms/zphp/releases). See the [documentation](https://nvms.github.io/zphp/) for building from source and detailed guides.
+Download builds from [GitHub Releases](https://github.com/nvms/zphp/releases).
+
+See the [documentation](https://nvms.github.io/zphp/) for build instructions and usage guides.
+
+## Project Status
+
+zphp was originally developed and maintained heavily through AI-assisted development.
+
+The project is now being actively reviewed and hardened with a stronger focus on **security, correctness, memory safety, testing, performance validation, and production readiness**.
+
+AI may still be used as a development tool, but critical runtime code is expected to be reviewed, tested, and independently verified.
+
+zphp is still experimental and should be thoroughly tested before production use.
---
-This project is an experiment in AI-maintained open source - autonomously built, tested, and refined by AI with human oversight.
+**PHP on the surface. Zig at the core. Built for speed.**
diff --git a/benchmarks/runtime/array_ops.php b/benchmarks/runtime/array_ops.php
index 2e68089d..63c628a4 100644
--- a/benchmarks/runtime/array_ops.php
+++ b/benchmarks/runtime/array_ops.php
@@ -2,19 +2,16 @@
// array operations - tests array creation, access, manipulation
$n = 50000;
-// build array
$arr = [];
for ($i = 0; $i < $n; $i++) {
$arr[] = $n - $i;
}
-// sum
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$sum += $arr[$i];
}
-// filter to new array
$filtered = [];
for ($i = 0; $i < $n; $i++) {
if ($arr[$i] % 3 === 0) {
@@ -22,7 +19,6 @@
}
}
-// map
$mapped = [];
for ($i = 0; $i < count($filtered); $i++) {
$mapped[] = $filtered[$i] * 2;
diff --git a/benchmarks/runtime/closures.php b/benchmarks/runtime/closures.php
index d185bb84..09782567 100644
--- a/benchmarks/runtime/closures.php
+++ b/benchmarks/runtime/closures.php
@@ -2,7 +2,6 @@
// closure operations - tests closure creation, invocation, captures
$n = 50000;
-// create and call closures
$adders = [];
for ($i = 0; $i < 100; $i++) {
$adders[] = function ($x) use ($i) { return $x + $i; };
@@ -13,12 +12,10 @@
$sum += $adders[$i % 100]($i);
}
-// higher-order: array_map with closure
$data = range(1, 10000);
$squared = array_map(function ($x) { return $x * $x; }, $data);
$total = array_sum($squared);
-// nested closures
function compose(callable $f, callable $g): callable {
return function ($x) use ($f, $g) { return $f($g($x)); };
}
diff --git a/benchmarks/runtime/loops.php b/benchmarks/runtime/loops.php
index ff85e500..7f47075c 100644
--- a/benchmarks/runtime/loops.php
+++ b/benchmarks/runtime/loops.php
@@ -2,14 +2,12 @@
// tight loop arithmetic - tests raw bytecode execution speed
$n = 5000000;
-// integer arithmetic loop
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$sum += $i;
}
echo "$sum\n";
-// nested loops with conditionals
$count = 0;
for ($i = 0; $i < 2000; $i++) {
for ($j = 0; $j < 2000; $j++) {
@@ -20,7 +18,6 @@
}
echo "$count\n";
-// while loop with mixed ops
$x = 1.0;
$i = 0;
while ($i < 1000000) {
diff --git a/benchmarks/runtime/objects.php b/benchmarks/runtime/objects.php
index 8d157379..bfc4744b 100644
--- a/benchmarks/runtime/objects.php
+++ b/benchmarks/runtime/objects.php
@@ -23,18 +23,15 @@ public function add(Point $other): Point {
$n = 50000;
$points = [];
-// create objects
for ($i = 0; $i < $n; $i++) {
$points[] = new Point($i * 0.1, $i * 0.2);
}
-// method calls
$totalDist = 0.0;
for ($i = 1; $i < $n; $i++) {
$totalDist += $points[$i]->distanceTo($points[$i - 1]);
}
-// chained operations
$sum = new Point(0, 0);
for ($i = 0; $i < 1000; $i++) {
$sum = $sum->add($points[$i]);
diff --git a/benchmarks/runtime/string_ops.php b/benchmarks/runtime/string_ops.php
index af4d1042..a2b6fdf1 100644
--- a/benchmarks/runtime/string_ops.php
+++ b/benchmarks/runtime/string_ops.php
@@ -8,13 +8,10 @@
$s .= "item" . $i . ",";
}
-// count occurrences
$count = substr_count($s, "item1");
-// replace
$replaced = str_replace("item", "elem", $s);
-// split and rejoin
$parts = explode(",", $s);
$joined = implode(";", $parts);
diff --git a/build.zig b/build.zig
index 159be8ac..03ebaa0a 100644
--- a/build.zig
+++ b/build.zig
@@ -174,10 +174,10 @@ fn addXxhashShim(b: *std.Build, mod: *std.Build.Module) void {
fn addIcuShim(b: *std.Build, mod: *std.Build.Module) void {
var flags = std.ArrayList([]const u8){};
defer flags.deinit(b.allocator);
- flags.append(b.allocator, "-std=c11") catch {};
+ flags.append(b.allocator, "-std=c11") catch return;
if (pkgConfigCflagsIncludes(b, "icu-i18n")) |inc| {
const flag = std.fmt.allocPrint(b.allocator, "-I{s}", .{inc}) catch return;
- flags.append(b.allocator, flag) catch {};
+ flags.append(b.allocator, flag) catch return;
}
mod.addCSourceFile(.{
.file = b.path("src/stdlib/icu_shim.c"),
@@ -188,10 +188,10 @@ fn addIcuShim(b: *std.Build, mod: *std.Build.Module) void {
// exposed in the C++ API. link libc++ once for the whole module
var cpp_flags = std.ArrayList([]const u8){};
defer cpp_flags.deinit(b.allocator);
- cpp_flags.append(b.allocator, "-std=c++17") catch {};
+ cpp_flags.append(b.allocator, "-std=c++17") catch return;
if (pkgConfigCflagsIncludes(b, "icu-i18n")) |inc| {
const flag = std.fmt.allocPrint(b.allocator, "-I{s}", .{inc}) catch return;
- cpp_flags.append(b.allocator, flag) catch {};
+ cpp_flags.append(b.allocator, flag) catch return;
}
mod.addCSourceFile(.{
.file = b.path("src/stdlib/icu_msg_shim.cpp"),
diff --git a/build.zig.zon b/build.zig.zon
index 63cb6062..3c104161 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -6,6 +6,8 @@
.paths = .{
"build.zig",
"build.zig.zon",
+ "LICENSE",
+ "README.md",
"src",
},
}
diff --git a/examples/api-client/main.php b/examples/api-client/main.php
index f181529e..4f272ff0 100644
--- a/examples/api-client/main.php
+++ b/examples/api-client/main.php
@@ -1,10 +1,4 @@
$resp) {
yield $name => $resp->toArray();
@@ -220,7 +213,6 @@ function responseStats(array $responses): Generator {
// simulate responses (connection will fail but that exercises error handling)
$responses = [];
-// test error handling path
$r1 = $client->get("http://127.0.0.1:1/api/users");
$responses['users'] = $r1;
echo "users ok: " . ($r1->ok() ? 'true' : 'false') . "\n";
@@ -236,38 +228,30 @@ function responseStats(array $responses): Generator {
$r3 = $client->get("http://127.0.0.1:1/api/users");
$responses['users_cached'] = $r3;
-// render summary
echo renderSummary($responses);
-// generator stats
foreach (responseStats($responses) as $name => $stats) {
echo "$name: status={$stats['status']} ok=" . ($stats['ok'] ? 'true' : 'false') . "\n";
}
-// logger output
$log = $logger->format();
$lines = explode("\n", trim($log));
echo "log entries: " . count($lines) . "\n";
-// verify timezone in log entries
$first = $lines[0];
echo "log has timezone: " . (strpos($first, 'EST') !== false || strpos($first, 'EDT') !== false ? 'true' : 'false') . "\n";
-// cache state
echo "cache keys: " . count($cache->keys()) . "\n";
-// datetime with timezone
$dt = new DateTime("now", new DateTimeZone("America/New_York"));
$tz = $dt->getTimezone();
echo "tz: " . $tz->getName() . "\n";
-// serializable interface
echo "r1 serializable: " . ($r1 instanceof Exportable ? 'true' : 'false') . "\n";
$arr = $r1->toArray();
echo "toArray has status: " . (isset($arr['status']) ? 'true' : 'false') . "\n";
echo "toArray has ok: " . (isset($arr['ok']) ? 'true' : 'false') . "\n";
-// enum match
$levels = [LogLevel::DEBUG, LogLevel::INFO, LogLevel::WARN, LogLevel::ERROR];
foreach ($levels as $l) {
$icon = match($l) {
@@ -280,7 +264,6 @@ function responseStats(array $responses): Generator {
}
echo "\n";
-// $argv / $argc
echo "argv type: " . gettype($argv) . "\n";
echo "argc type: " . gettype($argc) . "\n";
diff --git a/examples/array-deep-ops/main.php b/examples/array-deep-ops/main.php
index 817b6264..72a24ce5 100644
--- a/examples/array-deep-ops/main.php
+++ b/examples/array-deep-ops/main.php
@@ -1,7 +1,4 @@
['name' => 'Alice', 'tags' => ['admin']]];
diff --git a/examples/array-pointers/main.php b/examples/array-pointers/main.php
index 9b1b388d..cd2b820d 100644
--- a/examples/array-pointers/main.php
+++ b/examples/array-pointers/main.php
@@ -1,7 +1,5 @@
'apple', 'b' => 'banana', 'c' => 'cherry', 'd' => 'date'];
@@ -50,7 +47,6 @@
echo "after prev - current: " . current($assoc) . "\n";
echo "after prev - key: " . key($assoc) . "\n";
-// --- pointer past end ---
echo "\n=== Pointer past end ===\n";
$small = [100, 200];
@@ -66,7 +62,6 @@
reset($small);
echo "after reset from past-end: " . current($small) . "\n";
-// --- prev before start ---
echo "\n=== Pointer before start ===\n";
$small2 = [100, 200];
@@ -78,7 +73,6 @@
echo "key before start: ";
var_dump(key($small2));
-// --- empty array ---
echo "\n=== Empty array ===\n";
$empty = [];
@@ -95,7 +89,6 @@
echo "end on empty: ";
var_dump(end($empty));
-// --- single element ---
echo "\n=== Single element ===\n";
$single = ['only' => 42];
@@ -131,7 +124,6 @@
echo "arr1 after reset: " . current($arr1) . "\n";
echo "arr2 unchanged: " . current($arr2) . "\n";
-// --- walking with next ---
echo "\n=== Walking with next ===\n";
$walk = ['first', 'second', 'third'];
@@ -141,7 +133,6 @@
$val = next($walk);
}
-// --- pointer after unset ---
echo "\n=== Pointer after unset ===\n";
$mod = [10, 20, 30, 40, 50];
@@ -165,7 +156,6 @@
echo "after add - current: " . current($grow) . "\n";
echo "after add - key: " . key($grow) . "\n";
-// --- reset return value ---
echo "\n=== Reset and end return values ===\n";
$ret = [100, 200, 300];
diff --git a/examples/attribute-enforcement/main.php b/examples/attribute-enforcement/main.php
index 1547a183..c87550a0 100644
--- a/examples/attribute-enforcement/main.php
+++ b/examples/attribute-enforcement/main.php
@@ -1,8 +1,4 @@
newInstance();
echo "valid newInstance: " . $inst->val . "\n";
-// non-attribute class
class NotAnAttr {}
#[NotAnAttr]
@@ -32,7 +27,6 @@ class MyClass2 {}
echo "non-attr: caught\n";
}
-// target enforcement
#[Attribute(Attribute::TARGET_METHOD)]
class MethodOnly {
public function __construct(public string $val = '') {}
@@ -50,7 +44,6 @@ class MyClass3 {}
echo "target: caught\n";
}
-// repeatability enforcement
#[Attribute]
class SingleAttr {
public function __construct(public string $val = '') {}
@@ -85,7 +78,6 @@ class MyClass5 {}
$inst5b = $attrs5[1]->newInstance();
echo "repeatable: " . $inst5a->val . ", " . $inst5b->val . "\n";
-// #[Override] valid usage
class Base {
public function doStuff(): string { return 'base'; }
}
diff --git a/examples/attributes-enum-interface-trait/main.php b/examples/attributes-enum-interface-trait/main.php
index 5fbba1f6..5d4e50c3 100644
--- a/examples/attributes-enum-interface-trait/main.php
+++ b/examples/attributes-enum-interface-trait/main.php
@@ -1,10 +1,4 @@
getName() . "\n";
-// --- Interface attributes ---
echo "\n=== Interface Attributes ===\n";
@@ -133,7 +122,6 @@ public function touch(): void {
// note: getMethod on interfaces requires interface methods in ClassDef.methods
// which is tracked separately - test class-level attrs here
-// --- Trait attributes ---
echo "\n=== Trait Attributes ===\n";
diff --git a/examples/attributes-reflection/main.php b/examples/attributes-reflection/main.php
index 88b8887f..e23b5ac8 100644
--- a/examples/attributes-reflection/main.php
+++ b/examples/attributes-reflection/main.php
@@ -1,13 +1,4 @@
hasMethod('greet') ? 'true' : 'false') . "\n";
echo "hasMethod nonexistent: " . ($ref->hasMethod('nonexistent') ? 'true' : 'false') . "\n";
-// --- methods ---
echo "\n=== Methods ===\n";
@@ -98,7 +87,6 @@ public static function fromArray(array $data): self {
echo "all methods: " . implode(', ', $methodNames) . "\n";
echo "method count: " . count($methodNames) . "\n";
-// --- method visibility ---
echo "\n=== Method Visibility ===\n";
@@ -118,7 +106,6 @@ public static function fromArray(array $data): self {
$createM = $ref->getMethod('fromArray');
echo "fromArray isStatic: " . ($createM->isStatic() ? 'true' : 'false') . "\n";
-// --- parameters ---
echo "\n=== Parameters ===\n";
@@ -140,7 +127,6 @@ public static function fromArray(array $data): self {
echo $line . "\n";
}
-// --- properties ---
echo "\n=== Properties ===\n";
@@ -163,7 +149,6 @@ public static function fromArray(array $data): self {
$pwdProp = $ref->getProperty('password');
echo "password isPrivate: " . ($pwdProp->isPrivate() ? 'true' : 'false') . "\n";
-// --- practical: object inspector ---
echo "\n=== Object Inspector ===\n";
@@ -203,7 +188,6 @@ function inspect(object $obj): void {
$user = new User(1, 'Alice', 'alice@example.com');
inspect($user);
-// --- Attributes ---
echo "\n=== Attributes ===\n";
@@ -263,7 +247,6 @@ public function create() { return 'created'; }
echo "title attr 0: " . $titleAttrs[0]->getName() . "\n";
echo "title attr 0 arg: " . $titleAttrs[0]->getArguments()[0] . "\n";
-// newInstance
$routeAttr = $classAttrs[0];
$routeInstance = $routeAttr->newInstance();
echo "route instance class: " . get_class($routeInstance) . "\n";
diff --git a/examples/autoloader/main.php b/examples/autoloader/main.php
index 3524fcc3..75c62dce 100644
--- a/examples/autoloader/main.php
+++ b/examples/autoloader/main.php
@@ -1,6 +1,4 @@
), foreach references (&$entry), first-class callable syntax,
-// compact(), constructor property promotion, enums (eviction policy),
-// array destructuring with keys, match expressions, spread operator,
-// pass-by-reference (&$stats), heredoc, static methods
enum EvictionPolicy: string {
case LRU = 'lru';
@@ -136,7 +130,6 @@ private function evict(): void {
}
}
- // ArrayAccess
public function offsetExists(mixed $offset): bool {
return $this->has($offset);
}
@@ -153,7 +146,6 @@ public function offsetUnset(mixed $offset): void {
$this->delete($offset);
}
- // Countable
public function count(): int {
return count($this->entries);
}
@@ -213,7 +205,6 @@ public function collectStats(): array {
}
}
-// --- basic set/get ---
$cache = new Cache(maxSize: 5, policy: EvictionPolicy::LRU, defaultTtl: 3600);
@@ -227,7 +218,6 @@ public function collectStats(): array {
echo $cache->get('missing', 'default') . "\n";
echo "count: " . count($cache) . "\n";
-// --- ArrayAccess ---
$cache['color'] = 'blue';
echo $cache['color'] . "\n";
@@ -236,7 +226,6 @@ public function collectStats(): array {
echo "after unset: " . (isset($cache['color']) ? 'yes' : 'no') . "\n";
echo "count: " . count($cache) . "\n";
-// --- serialize complex values ---
$data = ['nested' => ['a' => 1, 'b' => [2, 3]], 'flag' => true, 'nothing' => null];
$cache->set('complex', $data);
@@ -246,7 +235,6 @@ public function collectStats(): array {
echo "flag: " . ($retrieved['flag'] ? 'true' : 'false') . "\n";
echo "nothing: " . ($retrieved['nothing'] === null ? 'null' : 'other') . "\n";
-// --- eviction (LRU) ---
$lru = new Cache(maxSize: 3, policy: EvictionPolicy::LRU);
$lru->set('a', 1);
@@ -259,7 +247,6 @@ public function collectStats(): array {
echo "b evicted: " . ($lru->has('b') ? 'no' : 'yes') . "\n";
echo "d exists: " . ($lru->has('d') ? 'yes' : 'no') . "\n";
-// --- eviction (FIFO) ---
$fifo = new Cache(maxSize: 3, policy: EvictionPolicy::FIFO);
$fifo->set('x', 10);
@@ -271,7 +258,6 @@ public function collectStats(): array {
echo "x evicted fifo: " . ($fifo->has('x') ? 'no' : 'yes') . "\n";
echo "z survived fifo: " . ($fifo->has('z') ? 'yes' : 'no') . "\n";
-// --- generator iteration ---
$cache->set('g1', 'alpha');
$cache->set('g2', 'beta');
@@ -284,14 +270,12 @@ public function collectStats(): array {
sort($items);
echo "entries: " . implode(', ', $items) . "\n";
-// --- pass-by-reference stats ---
$h = 0;
$m = 0;
$cache->stats($h, $m);
echo "hits: $h, misses: $m\n";
-// --- nullsafe operator ---
$group = new CacheGroup();
$group->add('main', $cache);
@@ -301,7 +285,6 @@ public function collectStats(): array {
$nope = $group->find('nonexistent')?->getPolicy();
echo "null policy: " . ($nope === null ? 'null' : 'other') . "\n";
-// --- enum features ---
echo EvictionPolicy::LRU->value . "\n";
echo EvictionPolicy::FIFO->label() . "\n";
@@ -323,7 +306,6 @@ public function collectStats(): array {
echo "group $name: $cnt items, $pol\n";
}
-// --- heredoc ---
$cacheName = 'main';
$cacheCount = count($cache);
@@ -334,7 +316,6 @@ public function collectStats(): array {
REPORT;
echo $report . "\n";
-// --- DateTime/strtotime ---
$base = 1750000000;
$expiry = strtotime("+1 hour", $base);
@@ -345,7 +326,6 @@ public function collectStats(): array {
$dt->modify('+30 minutes');
echo "modified: " . $dt->format('H:i') . "\n";
-// --- compact ---
$status = 'active';
$size = 5;
diff --git a/examples/calculator/main.php b/examples/calculator/main.php
index df5e0e41..91efb5d1 100644
--- a/examples/calculator/main.php
+++ b/examples/calculator/main.php
@@ -1,13 +1,5 @@
prop}",
-// "{$arr['key']}"), multi-level inheritance (grandparent->parent->child),
-// type juggling (string to number, loose comparison), switch with fallthrough,
-// nested ternary, str_split, substr, ctype_digit, ctype_alpha, ctype_space,
-// is_numeric, intval, floatval, number_format, abs, pow, sqrt, max, min,
-// array_reverse, array_key_exists, sprintf, compact, recursive array processing
-// --- token types ---
class Token
{
@@ -26,7 +18,6 @@ public function __toString(): string
}
}
-// --- lexer ---
class Lexer
{
@@ -260,7 +251,6 @@ public function display(): string
}
}
-// --- recursive descent parser ---
class Parser
{
@@ -293,7 +283,6 @@ private function eat(string $type): Token
return $tok;
}
- // expression: term ((+|-) term)*
private function parseExpression(): AstNode
{
$node = $this->parseTerm();
@@ -305,7 +294,6 @@ private function parseExpression(): AstNode
return $node;
}
- // term: power ((*|/|%) power)*
private function parseTerm(): AstNode
{
$node = $this->parsePower();
@@ -317,7 +305,6 @@ private function parseTerm(): AstNode
return $node;
}
- // power: unary (^ unary)*
private function parsePower(): AstNode
{
$node = $this->parseUnary();
@@ -329,7 +316,6 @@ private function parsePower(): AstNode
return $node;
}
- // unary: -unary | primary
private function parseUnary(): AstNode
{
if ($this->current()->type === "op" && $this->current()->value === "-") {
@@ -383,7 +369,6 @@ private function parsePrimary(): AstNode
}
}
-// --- evaluator helper ---
function calc(string $expr, array $env = []): string
{
@@ -398,7 +383,6 @@ function calc(string $expr, array $env = []): string
return number_format($result, 6, ".", "");
}
-// --- recursive helpers ---
function factorial(int $n): int
{
@@ -419,7 +403,6 @@ function flattenArray(array $arr): array
return $result;
}
-// === test: basic arithmetic ===
echo "1+2: " . calc("1 + 2") . "\n";
echo "10-3*2: " . calc("10 - 3 * 2") . "\n";
@@ -428,7 +411,6 @@ function flattenArray(array $arr): array
echo "10%3: " . calc("10 % 3") . "\n";
echo "-5+3: " . calc("-5 + 3") . "\n";
-// === test: function calls ===
echo "sqrt(144): " . calc("sqrt(144)") . "\n";
echo "abs(-42): " . calc("abs(-42)") . "\n";
@@ -446,7 +428,6 @@ function flattenArray(array $arr): array
echo "x+y: " . calc("x + y", ["x" => 10, "y" => 20]) . "\n";
echo "x^2+1: " . calc("x ^ 2 + 1", ["x" => 5]) . "\n";
-// === test: complex expressions ===
echo "nested: " . calc("(1 + 2) * (3 + 4) / (5 - 3)") . "\n";
echo "deep: " . calc("sqrt(pow(3, 2) + pow(4, 2))") . "\n";
@@ -464,7 +445,6 @@ function flattenArray(array $arr): array
$strs = array_map(function ($t) { return (string) $t; }, $tokens);
echo "tokens: " . implode(" ", $strs) . "\n";
-// === test: error handling ===
try {
calc("1 + + 2");
@@ -478,7 +458,6 @@ function flattenArray(array $arr): array
echo "error: " . $e->getMessage() . "\n";
}
-// === test: recursive functions ===
echo "5!: " . factorial(5) . "\n";
echo "10!: " . factorial(10) . "\n";
@@ -489,7 +468,6 @@ function flattenArray(array $arr): array
$flat = flattenArray($nested);
echo "flat: " . implode(", ", $flat) . "\n";
-// === test: nested closures ===
function makeAdder(int $n): Closure
{
@@ -503,7 +481,6 @@ function makeAdder(int $n): Closure
echo "add5(3): " . $add5(3) . "\n";
echo "add10(3): " . $add10(3) . "\n";
-// closure returning closure
function multiplierFactory(): Closure
{
return function (int $factor) {
@@ -518,7 +495,6 @@ function multiplierFactory(): Closure
echo "double(7): " . $double(7) . "\n";
echo "triple(7): " . $triple(7) . "\n";
-// === test: type juggling ===
echo "str+num: " . ("5" + 3) . "\n";
echo "str*num: " . ("4" * "3") . "\n";
diff --git a/examples/closure-binding/main.php b/examples/closure-binding/main.php
index 660b209d..85d98cc0 100644
--- a/examples/closure-binding/main.php
+++ b/examples/closure-binding/main.php
@@ -1,7 +1,4 @@
dump();
-// macro system using Closure::bind
class Collection {
public array $items;
public static array $macros = [];
@@ -105,7 +101,6 @@ public function __call(string $name, array $args): mixed {
echo "has 20: " . ($nums->contains(20) ? "yes" : "no") . "\n";
echo "has 99: " . ($nums->contains(99) ? "yes" : "no") . "\n";
-// bindTo for middleware-style pattern
class Request {
public string $method;
public string $path;
@@ -170,13 +165,11 @@ public function __construct(array $data) {
echo $reader->call($config, "port") . "\n";
echo $reader->call($config, "missing") . "\n";
-// Closure::fromCallable
function double(int $n): int { return $n * 2; }
$fn = Closure::fromCallable('double');
echo $fn(21) . "\n";
-// captured vars preserved across rebinding
$multiplier = 3;
$multiply = function(int $n) use ($multiplier) {
return $n * $multiplier + count($this->items);
diff --git a/examples/closure-introspection/main.php b/examples/closure-introspection/main.php
index 3d96b9dc..4905aaf6 100644
--- a/examples/closure-introspection/main.php
+++ b/examples/closure-introspection/main.php
@@ -1,7 +1,4 @@
getClosure(),
-// static closures, $this-less arrow funcs, closure use vs auto-capture
class Wallet {
private int $cents = 0;
diff --git a/examples/closures-advanced/main.php b/examples/closures-advanced/main.php
index 2549a69b..645011d1 100644
--- a/examples/closures-advanced/main.php
+++ b/examples/closures-advanced/main.php
@@ -1,12 +1,5 @@
$x * 2;
@@ -99,7 +89,6 @@ public function cube(int $n): int {
$addOneThenTriple = $compose($timesThree, $addOne);
echo "compose(triple, addOne)(4): " . $addOneThenTriple(4) . "\n";
-// --- first-class callable syntax ---
echo "\n=== First-Class Callable Syntax ===\n";
$strlen = strlen(...);
@@ -127,7 +116,6 @@ public static function lower(string $s): string {
$lowerFn = Formatter::lower(...);
echo "lower('WORLD'): " . $lowerFn('WORLD') . "\n";
-// --- recursive closures ---
echo "\n=== Recursive Closures ===\n";
$factorial = null;
@@ -202,7 +190,6 @@ function pipeline(array $fns): Closure {
]);
echo "pipeline(5): " . $transform(5) . "\n";
-// --- static closures ---
echo "\n=== Static Closures ===\n";
$static = static function(int $a, int $b): int {
@@ -213,7 +200,6 @@ function pipeline(array $fns): Closure {
$staticArrow = static fn(int $x) => $x * $x;
echo "static square(9): " . $staticArrow(9) . "\n";
-// --- array_reduce and array_walk ---
echo "\n=== array_reduce and array_walk ===\n";
$nums = [1, 2, 3, 4, 5];
@@ -238,7 +224,6 @@ function pipeline(array $fns): Closure {
}
echo implode(", ", $parts) . "\n";
-// --- variable function calls ---
echo "\n=== Variable Function Calls ===\n";
$fn = 'strlen';
@@ -250,7 +235,6 @@ function pipeline(array $fns): Closure {
$fn = 'array_sum';
echo "sum([1,2,3]): " . $fn([1, 2, 3]) . "\n";
-// --- is_callable checks ---
echo "\n=== is_callable Checks ===\n";
echo "closure: " . (is_callable(function() {}) ? "yes" : "no") . "\n";
diff --git a/examples/collection-pipeline/main.php b/examples/collection-pipeline/main.php
index d484539c..8788e668 100644
--- a/examples/collection-pipeline/main.php
+++ b/examples/collection-pipeline/main.php
@@ -1,12 +1,5 @@
1.50, 'banana' => 0.75, 'cherry' => 2.00];
array_walk($prices, function(&$price, $key) {
@@ -36,7 +28,6 @@
echo "$item: $price\n";
}
-// test 3: sorting functions
echo "\n=== Test 3: Sorting ===\n";
$data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
usort($data, fn($a, $b) => $a - $b);
@@ -56,7 +47,6 @@
foreach ($assoc as $k => $v) echo "$k=$v ";
echo "\n";
-// test 4: array_combine and array_column
echo "\n=== Test 4: Combine and Column ===\n";
$keys = ['name', 'age', 'city'];
$values = ['Alice', 30, 'NYC'];
@@ -76,7 +66,6 @@
$byName = array_column($people, null, 'name');
echo "Bob's age: " . $byName['Bob']['age'] . "\n";
-// test 5: compact and extract
echo "\n=== Test 5: Compact/Extract ===\n";
$name = "Alice";
$age = 30;
@@ -90,7 +79,6 @@
extract($record);
echo "Extract: color=$color, size=$size, count=$count\n";
-// test 6: set operations
echo "\n=== Test 6: Set Operations ===\n";
$a = [1, 2, 3, 4, 5];
$b = [3, 4, 5, 6, 7];
@@ -99,7 +87,6 @@
echo "Diff (b-a): " . implode(', ', array_diff($b, $a)) . "\n";
echo "Union: " . implode(', ', array_unique(array_merge($a, $b))) . "\n";
-// test 7: array manipulation
echo "\n=== Test 7: Array Manipulation ===\n";
$arr = [1, 2, 3, 4, 5];
echo "Reverse: " . implode(', ', array_reverse($arr)) . "\n";
@@ -114,7 +101,6 @@
echo "Pad to 8: " . implode(', ', array_pad($arr, 8, 0)) . "\n";
echo "Fill(0,5,x): " . implode(', ', array_fill(0, 5, 'x')) . "\n";
-// test 8: search and count
echo "\n=== Test 8: Search and Count ===\n";
$fruits = ['apple', 'banana', 'cherry', 'banana', 'date', 'banana'];
echo "Has banana: " . (in_array('banana', $fruits) ? 'yes' : 'no') . "\n";
@@ -126,7 +112,6 @@
$counts = array_count_values($fruits);
echo "Banana count: " . $counts['banana'] . "\n";
-// test 9: flip and unique
echo "\n=== Test 9: Flip and Unique ===\n";
$map = ['a' => 1, 'b' => 2, 'c' => 3];
$flipped = array_flip($map);
@@ -137,7 +122,6 @@
$dupes = [1, 2, 2, 3, 3, 3, 4];
echo "Unique: " . implode(', ', array_unique($dupes)) . "\n";
-// test 10: keys and values
echo "\n=== Test 10: Keys/Values ===\n";
$data = ['x' => 10, 'y' => 20, 'z' => 30];
echo "Keys: " . implode(', ', array_keys($data)) . "\n";
@@ -162,7 +146,6 @@
);
echo implode(', ', $labels) . "\n";
-// test 13: complex pipeline
echo "\n=== Test 13: Complex Pipeline ===\n";
$students = [
['name' => 'Alice', 'grade' => 92],
@@ -180,7 +163,6 @@
$avg = array_sum(array_column($students, 'grade')) / count($students);
echo "Class average: " . round($avg, 1) . "\n";
-// test 14: splice
echo "\n=== Test 14: Splice ===\n";
$arr = ['a', 'b', 'c', 'd', 'e'];
$removed = array_splice($arr, 1, 2, ['x', 'y', 'z']);
diff --git a/examples/color-converter/main.php b/examples/color-converter/main.php
index 51930469..804222e0 100644
--- a/examples/color-converter/main.php
+++ b/examples/color-converter/main.php
@@ -1,5 +1,4 @@
= 2) {
$first = $value[0];
$last = $value[strlen($value) - 1];
@@ -37,7 +35,6 @@ function parseIni(string $content): array {
}
}
- // type coercion
if (strtolower($value) === 'true' || strtolower($value) === 'on' || strtolower($value) === 'yes') {
$value = true;
} elseif (strtolower($value) === 'false' || strtolower($value) === 'off' || strtolower($value) === 'no') {
@@ -139,7 +136,6 @@ function deepMerge(array $base, array $override): array {
echo " cache.ttl: " . $merged['cache']['ttl'] . "\n";
echo " cache.driver: " . $merged['cache']['driver'] . "\n";
-// --- config path accessor ---
function configGet(array $config, string $path, $default = null) {
$keys = explode('.', $path);
@@ -178,7 +174,6 @@ function configSet(array $config, string $path, $value): array {
echo " database.pool_size: " . configGet($merged, 'database.pool_size') . "\n";
echo " new.nested.value: " . configGet($merged, 'new.nested.value') . "\n";
-// --- config validation ---
function validateConfig(array $config, array $schema): array {
$errors = [];
@@ -250,7 +245,6 @@ function validateConfig(array $config, array $schema): array {
echo " $err\n";
}
-// --- compact/extract ---
$host = 'localhost';
$port = 5432;
diff --git a/examples/config-loader/main.php b/examples/config-loader/main.php
index dce35c16..dc6fe6cb 100644
--- a/examples/config-loader/main.php
+++ b/examples/config-loader/main.php
@@ -1,11 +1,4 @@
"myapp", "debug" => false];
$override = ["debug" => true, "version" => "1.0"];
@@ -213,7 +203,6 @@ function joinAll(string $sep, string ...$parts): string
$items = ["a", "b", "c"];
echo "spread call: " . joinAll("-", ...$items) . "\n";
-// === test: named arguments ---
function formatEntry(string $key, string $value, string $separator = ": "): string
{
@@ -239,7 +228,6 @@ function formatEntry(string $key, string $value, string $separator = ": "): stri
$settings["theme"] ??= "light";
echo "nullish: " . $settings["theme"] . "\n";
-// === test: clone ===
$original = new Config();
$original->set("key1", "val1");
@@ -251,7 +239,6 @@ function formatEntry(string $key, string $value, string $separator = ": "): stri
echo "original: " . $original->get("key1") . "\n";
echo "cloned: " . $cloned->get("key1") . "\n";
-// === test: type casting ===
$cv = new ConfigValue("port", "8080");
echo "readonly: " . $cv->key . " type=" . $cv->type . "\n";
@@ -261,7 +248,6 @@ function formatEntry(string $key, string $value, string $separator = ": "): stri
$cv2 = new ConfigValue("flag", "1");
echo "cast bool: " . ($cv2->cast("bool") ? "true" : "false") . "\n";
-// === test: serialize/unserialize ===
$data = ["host" => "localhost", "port" => 5432, "debug" => true];
$serialized = serialize($data);
@@ -275,13 +261,11 @@ function formatEntry(string $key, string $value, string $separator = ": "): stri
$vars = ["name" => "World", "place" => "zphp"];
echo interpolate($template, $vars) . "\n";
-// === test: static variables ===
echo generateId() . "\n";
echo generateId() . "\n";
echo generateId() . "\n";
-// === test: class constants ===
echo "separator: " . Config::SEPARATOR . "\n";
echo "max depth: " . Config::MAX_DEPTH . "\n";
@@ -297,13 +281,11 @@ function formatEntry(string $key, string $value, string $separator = ": "): stri
$resolved = $config2->resolve();
echo "resolved: host=" . $resolved["host"] . " port=" . $resolved["port"] . " timeout=" . $resolved["timeout"] . " debug=" . ($resolved["debug"] ? "yes" : "no") . "\n";
-// === test: date/time ===
$ts = mktime(14, 30, 0, 6, 15, 2025);
echo "date: " . date("Y-m-d", $ts) . "\n";
echo "time: " . date("H:i:s", $ts) . "\n";
-// === test: sprintf ===
echo sprintf("config has %d entries, version %s\n", 7, "1.0");
diff --git a/examples/config-merge/main.php b/examples/config-merge/main.php
index 8536efb6..4dccba1b 100644
--- a/examples/config-merge/main.php
+++ b/examples/config-merge/main.php
@@ -1,8 +1,4 @@
[
@@ -54,7 +50,6 @@
'debug' => true,
];
-// array_replace_recursive: deep merge configs
$config = array_replace_recursive($defaults, $environment, $overrides);
echo "=== merged config ===\n";
@@ -81,12 +76,10 @@ function printConfig(array $config, string $prefix = ''): void
echo "\n=== database config only ===\n";
printConfig($dbOnly);
-// array_diff_key: everything except database
$rest = array_diff_key($config, $dbKeys);
echo "\n=== non-database config ===\n";
printConfig($rest);
-// compact/extract
$host = $config['database']['host'];
$port = $config['database']['port'];
$driver = $config['cache']['driver'];
@@ -98,13 +91,11 @@ function printConfig(array $config, string $prefix = ''): void
echo " $k = $v\n";
}
-// extract into scope
$data = ['app_name' => 'MyApp', 'version' => '2.1.0', 'env' => 'production'];
extract($data);
echo "\n=== extract ===\n";
echo " $app_name v$version ($env)\n";
-// array_walk_recursive: collect all leaf values
$leaves = [];
array_walk_recursive($config, function ($value) use (&$leaves) {
$leaves[] = $value;
@@ -120,7 +111,6 @@ function printConfig(array $config, string $prefix = ''): void
echo " author: " . implode(', ', $merged['meta']['author']) . "\n";
echo " year: " . $merged['meta']['year'] . "\n";
-// verify key preservation through operations
$original_keys = array_keys($defaults);
$merged_keys = array_keys($config);
sort($original_keys);
diff --git a/examples/control-flow-nesting/main.php b/examples/control-flow-nesting/main.php
index f0fd0d33..b9af6c8f 100644
--- a/examples/control-flow-nesting/main.php
+++ b/examples/control-flow-nesting/main.php
@@ -1,7 +1,4 @@
" . strlen($binary) . " bytes -> " . bin2hex($binary) . "\n";
-// hmac signing
echo "\n=== HMAC signing ===\n";
$secret = "my-secret-key-2024";
$payloads = [
@@ -59,7 +52,6 @@
echo "key1 vs key2: " . ($sigs[0] === $sigs[1] ? 'same' : 'different') . "\n";
echo "key1 vs key1: " . ($sigs[0] === $sigs[2] ? 'same' : 'different') . "\n";
-// hash_equals: timing-safe comparison
echo "\n=== hash_equals (timing-safe) ===\n";
$known_hash = hash('sha256', 'correct-password');
@@ -80,10 +72,8 @@
$label, $expected ? 'true' : 'false', $result ? 'true' : 'false', $status);
}
-// different lengths always return false
echo " length mismatch: " . (hash_equals("abc", "ab") ? 'true' : 'false') . "\n";
-// webhook signature verification pattern
echo "\n=== webhook verification ===\n";
function verifyWebhook(string $payload, string $signature, string $secret): bool {
$expected = hash_hmac('sha256', $payload, $secret);
@@ -128,12 +118,10 @@ function validateToken(string $token, string $secret): array {
echo "valid: " . ($check['valid'] ? 'yes' : 'no') . "\n";
echo "user: " . $check['user'] . "\n";
-// tamper with token
$tampered = str_replace("user_42", "user_99", $token);
$check2 = validateToken($tampered, $secret);
echo "tampered valid: " . ($check2['valid'] ? 'yes' : 'no') . "\n";
-// checksum verification
echo "\n=== data integrity ===\n";
$files = [
'config.json' => '{"db":"localhost","port":5432}',
diff --git a/examples/csv-edge/main.php b/examples/csv-edge/main.php
index ff7d560c..ad871670 100644
--- a/examples/csv-edge/main.php
+++ b/examples/csv-edge/main.php
@@ -1,7 +1,4 @@
0, '$75K-$100K' => 0, 'Over $100K' => 0];
foreach ($rows as $row) {
@@ -98,7 +93,6 @@
echo " " . str_pad($band, 12) . " $bar ($count)\n";
}
-// formatted table
echo "\nFull Roster:\n";
echo sprintf(" %-10s %-14s %10s %6s\n", 'Name', 'Department', 'Salary', 'Years');
echo " " . str_repeat('-', 42) . "\n";
diff --git a/examples/csv-streaming/main.php b/examples/csv-streaming/main.php
index dbacc92a..b16b2f73 100644
--- a/examples/csv-streaming/main.php
+++ b/examples/csv-streaming/main.php
@@ -1,7 +1,4 @@
0 ? "string" : "missing");
diff --git a/examples/data-export/main.php b/examples/data-export/main.php
index 513fb955..ca066a3f 100644
--- a/examples/data-export/main.php
+++ b/examples/data-export/main.php
@@ -1,14 +1,8 @@
1, 'name' => 'Alice Chen', 'department' => 'Engineering', 'salary' => 125000, 'start_date' => '2020-03-15'],
['id' => 2, 'name' => 'Bob Kumar', 'department' => 'Marketing', 'salary' => 95000, 'start_date' => '2021-07-01'],
@@ -20,7 +14,6 @@
['id' => 8, 'name' => 'Hank Brown', 'department' => 'Engineering', 'salary' => 118000, 'start_date' => '2022-08-01'],
];
-// write CSV
echo "=== CSV export ===\n";
$csv_file = "$tmp/employees.csv";
$fp = fopen($csv_file, 'w');
@@ -35,7 +28,6 @@
echo "size: " . $info['size'] . " bytes\n";
echo "rows: " . count($employees) . " data + 1 header\n";
-// read CSV back and verify
echo "\n=== CSV import ===\n";
$fp = fopen($csv_file, 'r');
$headers = fgetcsv($fp);
@@ -55,7 +47,6 @@
echo "imported " . count($imported) . " rows\n";
echo "roundtrip match: " . (count($imported) === count($employees) ? 'yes' : 'no') . "\n";
-// department summary report
echo "\n=== department summary ===\n";
$dept_stats = [];
foreach ($employees as $emp) {
@@ -84,7 +75,6 @@
number_format($stats['max_salary'], 0, '.', ','));
}
-// total
$total_salary = array_sum(array_column($employees, 'salary'));
$avg_salary = round($total_salary / count($employees));
echo " " . str_repeat("-", 72) . "\n";
@@ -111,7 +101,6 @@
}
fclose($fp);
-// multi-file export report
echo "\n=== export summary ===\n";
$files = [$csv_file, $rank_file];
foreach ($files as $f) {
@@ -119,7 +108,6 @@
echo sprintf(" %-30s %6d bytes\n", basename($f), $s['size']);
}
-// generate a fixed-width report
echo "\n=== fixed-width report ===\n";
$report_file = "$tmp/report.txt";
$fp = fopen($report_file, 'w');
@@ -142,7 +130,6 @@
echo file_get_contents($report_file);
-// cleanup
foreach ($files as $f) unlink($f);
unlink($report_file);
rmdir($tmp);
diff --git a/examples/data-pipeline/main.php b/examples/data-pipeline/main.php
index c21191b9..8410ce74 100644
--- a/examples/data-pipeline/main.php
+++ b/examples/data-pipeline/main.php
@@ -1,16 +1,4 @@
floatval($r[$field] ?? 0), $rows);
$count = count($values);
@@ -195,7 +182,6 @@ function summarize(array $rows, string $field): Generator {
yield 'avg' => round(array_sum($values) / $count, 2);
}
-// format table using output buffering
function formatTable(array $rows, array $columns): string {
if (count($rows) === 0) return "(empty)\n";
@@ -211,7 +197,6 @@ function formatTable(array $rows, array $columns): string {
}
ob_start();
- // header
$parts = [];
foreach ($columns as $col) {
$parts[] = str_pad($col, $widths[$col]);
@@ -222,7 +207,6 @@ function formatTable(array $rows, array $columns): string {
$parts[] = str_repeat("-", $widths[$col]);
}
echo implode("-+-", $parts) . "\n";
- // rows
foreach ($rows as $row) {
$parts = [];
foreach ($columns as $col) {
@@ -233,7 +217,6 @@ function formatTable(array $rows, array $columns): string {
return ob_get_clean();
}
-// --- test data ---
$csv = "name, age, score, department
Alice, 28, 92.5, engineering
Bob, 34, 87.3, marketing
@@ -246,7 +229,6 @@ function formatTable(array $rows, array $columns): string {
Ivy, 33, 84.6, marketing
Jack, 38, 77.8, sales";
-// parse and apply schema
$schema = (new Schema())
->add(new Column('name', DataType::STRING))
->add(new Column('age', DataType::INT))
@@ -281,13 +263,11 @@ function formatTable(array $rows, array $columns): string {
echo "--- engineering (sorted by score, graded) ---\n";
echo formatTable($result, ['name', 'age', 'score', 'department']);
-// stats on all rows
echo "--- score stats (all departments) ---\n";
foreach (summarize($rows, 'score') as $stat => $value) {
echo " $stat: $value\n";
}
-// group by department using array_reduce
$grouped = array_reduce($rows, function($acc, $row) {
$dept = $row['department'];
if (!isset($acc[$dept])) $acc[$dept] = [];
@@ -301,7 +281,6 @@ function formatTable(array $rows, array $columns): string {
echo " $dept: " . implode(", ", $names) . "\n";
}
-// array operations
$names = array_column($rows, 'name');
echo "\nnames: " . implode(", ", $names) . "\n";
@@ -315,7 +294,6 @@ function formatTable(array $rows, array $columns): string {
sort($unique_depts);
echo "departments: " . implode(", ", $unique_depts) . "\n";
-// test compact/extract
$total = count($rows);
$avg_age = round(array_sum($ages) / $total);
$summary = compact('total', 'avg_age');
@@ -324,23 +302,19 @@ function formatTable(array $rows, array $columns): string {
extract($summary);
echo "extract: total=$total avg_age=$avg_age\n";
-// list destructuring
[$first, $second] = $rows;
echo "first: {$first['name']}, second: {$second['name']}\n";
-// array_walk
$scores_formatted = array_column($rows, 'score');
array_walk($scores_formatted, function(&$v) {
$v = number_format($v, 1);
});
echo "scores: " . implode(", ", $scores_formatted) . "\n";
-// array_chunk
$chunks = array_chunk($names, 3);
echo "chunks: " . count($chunks) . "\n";
echo "chunk[0]: " . implode(", ", $chunks[0]) . "\n";
-// string operations on names
$upper_names = array_map('strtoupper', array_slice($names, 0, 3));
echo "upper: " . implode(", ", $upper_names) . "\n";
diff --git a/examples/data-structures/main.php b/examples/data-structures/main.php
index 77050225..4f9c6665 100644
--- a/examples/data-structures/main.php
+++ b/examples/data-structures/main.php
@@ -1,7 +1,5 @@
size() . "\n";
echo " remaining: " . implode(', ', $stack->toArray()) . "\n";
-// --- queue (FIFO) ---
class Queue {
private array $items = [];
@@ -93,7 +90,6 @@ public function toArray(): array {
echo " dequeue: " . $queue->dequeue() . "\n";
echo " size: " . $queue->size() . "\n";
-// --- priority queue ---
class PriorityQueue {
private array $items = [];
@@ -128,7 +124,6 @@ public function size(): int {
echo " " . $pq->extract() . "\n";
}
-// --- linked list ---
class ListNode {
public $value;
@@ -229,7 +224,6 @@ public function reverse(): void {
echo " removeFirst: " . $list->removeFirst() . "\n";
echo " items: " . implode(' -> ', $list->toArray()) . "\n";
-// --- ring buffer ---
class RingBuffer {
private array $buffer;
@@ -288,7 +282,6 @@ public function toArray(): array {
echo " read: " . $ring->read() . "\n";
echo " remaining: " . implode(', ', $ring->toArray()) . "\n";
-// --- trie ---
class TrieNode {
public array $children = [];
@@ -370,7 +363,6 @@ private function collectWords(TrieNode $node, string $prefix, array &$words): vo
echo " words with 'app': " . implode(', ', $trie->wordsWithPrefix('app')) . "\n";
echo " words with 'b': " . implode(', ', $trie->wordsWithPrefix('b')) . "\n";
-// --- array utility functions ---
echo "\nArray utilities:\n";
diff --git a/examples/data-uri/main.php b/examples/data-uri/main.php
index 0ecec1ec..eb17a818 100644
--- a/examples/data-uri/main.php
+++ b/examples/data-uri/main.php
@@ -1,7 +1,4 @@
y/$diff->m/$diff->d/$diff->h/$diff->i/$diff->s\n";
echo "invert (start>end): " . $diff->invert . "\n";
-// reverse should invert
$diff2 = $end->diff($start);
echo "reverse invert: " . $diff2->invert . "\n";
diff --git a/examples/date-time/main.php b/examples/date-time/main.php
index 1a9fbd2a..df05bb76 100644
--- a/examples/date-time/main.php
+++ b/examples/date-time/main.php
@@ -1,9 +1,5 @@
get('Logger');
$log->log('INFO', 'Container initialized');
@@ -153,20 +140,16 @@ public function has(string $name): bool {
$c2 = $container->get('Cache');
echo " cache singleton check: " . ($c2->get('greeting') === 'hello from DI' ? 'ok' : 'fail') . "\n";
-// verify singleton identity
echo " same instance: " . (spl_object_id($c1) === spl_object_id($c2) ? 'yes' : 'no') . "\n";
-// dispatch an event
$dispatcher = $container->get('EventDispatcher');
$dispatcher->dispatch('user.login', ['user' => 'admin']);
-// container has checks
echo "\n=== container has ===\n";
echo "has Logger: " . ($container->has('Logger') ? 'yes' : 'no') . "\n";
echo "has Cache: " . ($container->has('Cache') ? 'yes' : 'no') . "\n";
echo "has Database: " . ($container->has('Database') ? 'yes' : 'no') . "\n";
-// get_class on resolved instances
echo "\n=== resolved types ===\n";
$services = ['Logger', 'Cache', 'EventDispatcher'];
foreach ($services as $name) {
@@ -174,7 +157,6 @@ public function has(string $name): bool {
echo sprintf(" %-20s -> %s\n", $name, get_class($instance));
}
-// method_exists on resolved instances
echo "\n=== method checks ===\n";
echo "Logger->log: " . (method_exists($log, 'log') ? 'yes' : 'no') . "\n";
echo "Logger->get: " . (method_exists($log, 'get') ? 'yes' : 'no') . "\n";
diff --git a/examples/di-container/main.php b/examples/di-container/main.php
index ff969dee..38fd02ad 100644
--- a/examples/di-container/main.php
+++ b/examples/di-container/main.php
@@ -1,10 +1,4 @@
bind('Logger', 'ConsoleLogger');
$container->singleton('Database', 'Database');
-// resolve a complex dependency tree
$repo = $container->make('UserRepository');
echo $repo->find(42) . "\n";
-// singleton check - same instance
$db1 = $container->make('Database');
$db2 = $container->make('Database');
echo ($db1 === $db2 ? "same" : "different") . " instance\n";
-// reflection introspection
$rc = new ReflectionClass('UserRepository');
echo "class: " . $rc->getName() . "\n";
echo "methods: " . count($rc->getMethods()) . "\n";
@@ -134,7 +124,6 @@ private function build(string $concrete): object {
echo "constructor declaring class: " . $ctor->getDeclaringClass()->getName() . "\n";
echo "constructor required params: " . $ctor->getNumberOfRequiredParameters() . "\n";
-// ReflectionFunction
function greet(string $name, string $greeting = "Hello"): string {
return "$greeting, $name!";
}
@@ -156,7 +145,6 @@ function greet(string $name, string $greeting = "Hello"): string {
echo "\n";
}
-// parent class and interface checks
$drc = new ReflectionClass('Database');
echo "Database parent: " . ($drc->getParentClass() === false ? "none" : $drc->getParentClass()->getName()) . "\n";
diff --git a/examples/diff-tool/main.php b/examples/diff-tool/main.php
index f59c978b..ad477a8c 100644
--- a/examples/diff-tool/main.php
+++ b/examples/diff-tool/main.php
@@ -1,8 +1,4 @@
$context * 2) {
- // close hunk, trim trailing context
$trim = $idle - $context;
$cur['ops'] = array_slice($cur['ops'], 0, count($cur['ops']) - $trim);
$hunks[] = $cur;
diff --git a/examples/dom-mutation/main.php b/examples/dom-mutation/main.php
index c79fe8ce..6742c0a3 100644
--- a/examples/dom-mutation/main.php
+++ b/examples/dom-mutation/main.php
@@ -1,7 +1,4 @@
formatOutput = false;
diff --git a/examples/edge-cases-runtime/main.php b/examples/edge-cases-runtime/main.php
index 206734e8..b8520745 100644
--- a/examples/edge-cases-runtime/main.php
+++ b/examples/edge-cases-runtime/main.php
@@ -1,9 +1,5 @@
id;
}
- // late static binding for factory
public static function create(array $attrs = []): static
{
return new static($attrs);
}
}
-// --- concrete entities ---
class User extends Entity
{
@@ -271,7 +261,6 @@ public function pluck(string $key): Collection
}
}
-// --- bitwise flags ---
const PERM_READ = 1;
const PERM_WRITE = 2;
@@ -294,7 +283,6 @@ function describePermissions(int $perms): string
return implode(", ", $names);
}
-// --- custom exceptions ---
class ValidationException extends RuntimeException
{
@@ -325,9 +313,7 @@ function saveEntity(Entity $entity, int $permissions): void
}
}
-// ============================================================
// tests
-// ============================================================
// === test: entity creation with late static binding ===
@@ -373,7 +359,6 @@ function saveEntity(Entity $entity, int $permissions): void
$evens = $numbers(function ($n) { return $n % 2 === 0; });
echo "evens: " . implode(", ", $evens->toArray()) . "\n";
-// === test: collection methods ===
$users = new Collection([
["name" => "Alice", "age" => 30],
@@ -383,7 +368,6 @@ function saveEntity(Entity $entity, int $permissions): void
$names = $users->pluck("name");
echo "names: " . implode(", ", $names->toArray()) . "\n";
-// === test: bitwise operations ===
$perms = PERM_READ | PERM_WRITE;
echo "perms: " . describePermissions($perms) . "\n";
@@ -431,7 +415,6 @@ function riskyOperation(): void
}
riskyOperation();
-// === test: do-while ===
$i = 1;
$sum = 0;
@@ -463,7 +446,6 @@ function riskyOperation(): void
}
echo "continue 2: " . implode(" ", $result) . "\n";
-// === test: __clone magic ===
$original = User::create(["name" => "CloneMe", "email" => "clone@test.com"]);
$original->setMeta("source", "original");
diff --git a/examples/enum-patterns/main.php b/examples/enum-patterns/main.php
index f7c96298..e9b9556d 100644
--- a/examples/enum-patterns/main.php
+++ b/examples/enum-patterns/main.php
@@ -1,7 +1,5 @@
name . " = " . $case->value . "\n";
}
-// --- enum methods ---
enum Direction {
case North;
@@ -101,7 +95,6 @@ public function label(): string {
echo "North label: " . $dir->label() . "\n";
echo "East opposite: " . Direction::East->opposite()->name . "\n";
-// --- enum implementing interfaces ---
interface HasDescription {
public function description(): string;
@@ -128,7 +121,6 @@ public function description(): string {
echo "Season value: " . $season->value . "\n";
echo "Season description: " . $season->description() . "\n";
-// --- enum constants ---
enum Size {
case Small;
@@ -156,7 +148,6 @@ function describeStatus(HttpStatus $s): string {
echo "404 status: " . describeStatus(HttpStatus::NotFound) . "\n";
echo "500 status: " . describeStatus(HttpStatus::ServerError) . "\n";
-// --- enum in arrays ---
$statusMessages = [];
$statusMessages[HttpStatus::OK->value] = "All good";
@@ -171,7 +162,6 @@ function describeStatus(HttpStatus $s): string {
echo "First favorite: " . $favorites[0]->name . "\n";
echo "Second favorite: " . $favorites[1]->name . "\n";
-// --- enum static methods ---
enum Currency: string {
case USD = 'USD';
@@ -209,7 +199,6 @@ public function symbol(): string {
}
echo "Unknown symbol throws: " . ($caughtSymbol ? "true" : "false") . "\n";
-// --- enum comparison ---
$a = Suit::Hearts;
$b = Suit::Hearts;
diff --git a/examples/enum-state-machine/main.php b/examples/enum-state-machine/main.php
index cfa40724..b62bf5cf 100644
--- a/examples/enum-state-machine/main.php
+++ b/examples/enum-state-machine/main.php
@@ -1,7 +1,4 @@
throw new TypeError("t"),
diff --git a/examples/error-recovery/main.php b/examples/error-recovery/main.php
index d3fd140f..c97d24e9 100644
--- a/examples/error-recovery/main.php
+++ b/examples/error-recovery/main.php
@@ -1,9 +1,5 @@
getMessage() : 'none') . "\n";
}
-// --- finally with return ---
echo "\n=== finally ===\n";
function withFinally($fail) {
$result = "start";
diff --git a/examples/event-dispatcher/main.php b/examples/event-dispatcher/main.php
index 1615d888..1302d81d 100644
--- a/examples/event-dispatcher/main.php
+++ b/examples/event-dispatcher/main.php
@@ -1,7 +1,4 @@
listen("user.created", $userHandler, 10);
$dispatcher->listen("user.created", $auditLogger, 5);
-// register closure listener
$createdNames = [];
$dispatcher->listen("user.created", function (EventInterface $event) use (&$createdNames) {
$createdNames[] = $event->get("name");
}, 1);
-// register listener for different event
$deletedLog = [];
$dispatcher->listen("user.deleted", function (EventInterface $event) use (&$deletedLog) {
$deletedLog[] = $event->get("name") . " was deleted";
});
-// dispatch events
$event1 = new Event("user.created", ["name" => "Alice", "email" => "alice@test.com"]);
$dispatcher->dispatch($event1);
@@ -181,7 +173,6 @@ public function getEntries(): array
$event3 = new Event("user.deleted", ["name" => "Charlie"]);
$dispatcher->dispatch($event3);
-// check results
echo "notifications:\n";
foreach ($userHandler->getNotifications() as $n) echo " $n\n";
@@ -191,7 +182,6 @@ public function getEntries(): array
echo "created: " . implode(", ", $createdNames) . "\n";
echo "deleted: " . implode(", ", $deletedLog) . "\n";
-// test priority ordering
$order = [];
$d2 = new EventDispatcher();
$d2->listen("test", function ($e) use (&$order) { $order[] = "low"; }, 1);
@@ -200,7 +190,6 @@ public function getEntries(): array
$d2->dispatch(new Event("test"));
echo "priority order: " . implode(", ", $order) . "\n";
-// test propagation stopping
$stopped = [];
$d3 = new EventDispatcher();
$d3->listen("stop.test", function (EventInterface $e) use (&$stopped) {
@@ -213,11 +202,9 @@ public function getEntries(): array
$d3->dispatch(new Event("stop.test"));
echo "stopped after: " . implode(", ", $stopped) . "\n";
-// test hasListeners
echo "has user.created: " . var_export($dispatcher->hasListeners("user.created"), true) . "\n";
echo "has unknown: " . var_export($dispatcher->hasListeners("unknown"), true) . "\n";
-// test event data mutation
$mutator = new EventDispatcher();
$mutator->listen("transform", function (EventInterface $e) {
$val = $e->get("value");
@@ -232,12 +219,10 @@ public function getEntries(): array
$mutator->dispatch($te);
echo "transformed: " . $te->get("value") . "\n";
-// test dispatch log
$log = $dispatcher->getLog();
echo "dispatched events: " . count($log) . "\n";
foreach ($log as $entry) echo " $entry\n";
-// test try/catch in listener
$errorDispatcher = new EventDispatcher();
$errorResults = [];
$errorDispatcher->listen("risky", function ($e) use (&$errorResults) {
diff --git a/examples/event-system/main.php b/examples/event-system/main.php
index e4217eda..f73f7210 100644
--- a/examples/event-system/main.php
+++ b/examples/event-system/main.php
@@ -1,5 +1,4 @@
once('notify', function(string $msg) use (&$onceLog) {
$onceLog[] = $msg;
@@ -128,7 +125,6 @@ public function format(): array {
echo "Once listener fired: " . count($onceLog) . " time(s)\n";
echo "Once value: " . $onceLog[0] . "\n";
-// listener count
$emitter->on('data', function() {});
$emitter->on('data', function() {});
echo "Data listeners: " . $emitter->listenerCount('data') . "\n";
@@ -155,7 +151,6 @@ public function format(): array {
echo " Count: " . count($errors) . "\n";
echo " Message: " . $errors[0]['message'] . "\n";
-// --- middleware pipeline ---
function pipeline(array $middlewares, $input) {
$next = function($value) { return $value; };
@@ -231,7 +226,6 @@ public function update(Subject $subject): void {
echo "\nObserver A received: " . implode(', ', $obs1->received) . "\n";
echo "Observer B received: " . implode(', ', $obs2->received) . "\n";
-// --- closure composition ---
function compose(callable ...$fns): callable {
return function($x) use ($fns) {
@@ -250,7 +244,6 @@ function compose(callable ...$fns): callable {
$transform = compose($square, $addOne, $double);
echo "\nCompose (5): " . $transform(5) . "\n";
-// --- currying ---
function curry(callable $fn, ...$initial): callable {
return function() use ($fn, $initial) {
diff --git a/examples/facade-pattern/main.php b/examples/facade-pattern/main.php
index 8037269f..1b549e9e 100644
--- a/examples/facade-pattern/main.php
+++ b/examples/facade-pattern/main.php
@@ -1,7 +1,4 @@
),
-// recursive closures, closure as return value, closure composition
-// --- higher-order functions ---
echo "=== Higher-Order Functions ===\n";
@@ -25,7 +19,6 @@ function($s) { return preg_replace('/[^a-z0-9-]/', '', $s); }
);
echo "piped: $result\n";
-// --- closure factories ---
echo "\n=== Closure Factories ===\n";
@@ -64,7 +57,6 @@ function makeCounter() {
$counter['reset']();
echo "after reset: " . $counter['get']() . "\n";
-// --- map/filter/reduce pipeline ---
echo "\n=== Pipeline ===\n";
@@ -97,7 +89,6 @@ function makeCounter() {
}, 0);
echo "grand total: \$" . number_format($grand, 2) . "\n";
-// --- compact/extract ---
echo "\n=== Compact/Extract ===\n";
@@ -114,7 +105,6 @@ function makeCounter() {
extract($other);
echo "extracted: color=$color, food=$food\n";
-// --- call_user_func ---
echo "\n=== Call User Func ===\n";
@@ -134,7 +124,6 @@ public function lower($s) { return strtolower($s); }
$fmt = new Formatter();
echo call_user_func([$fmt, 'lower'], 'WORLD') . "\n";
-// --- recursive closure ---
echo "\n=== Recursive Closure ===\n";
@@ -149,7 +138,6 @@ public function lower($s) { return strtolower($s); }
}
echo "fibonacci: " . implode(', ', $fibs) . "\n";
-// --- array_walk with ref ---
echo "\n=== Array Walk ===\n";
@@ -175,7 +163,6 @@ public function lower($s) { return strtolower($s); }
$strings = array_map(function($v) { return (string)((int)$v * 2); }, $values);
echo "doubled strings: " . implode(', ', $strings) . "\n";
-// --- named arguments ---
echo "\n=== Named Arguments ===\n";
@@ -190,7 +177,6 @@ function createTag($tag, $content, $class = '', $id = '') {
echo createTag('p', 'World', class: 'highlight') . "\n";
echo createTag('span', 'Test', id: 'main', class: 'bold') . "\n";
-// --- memoize pattern ---
echo "\n=== Memoize ===\n";
diff --git a/examples/generator-edges/main.php b/examples/generator-edges/main.php
index 460ed70b..cb988c66 100644
--- a/examples/generator-edges/main.php
+++ b/examples/generator-edges/main.php
@@ -1,7 +1,4 @@
withHeader("Accept", "application/json")
@@ -137,20 +132,17 @@ public static function report($ch): void {
$ch3 = $delete->toCurl();
RequestInspector::report($ch3);
-// test curl_reset
echo "\n--- reset ---\n";
curl_reset($ch);
$info = curl_getinfo($ch);
echo "after reset url: '" . ($info['url'] ?? '') . "'\n";
echo "after reset error: '" . curl_error($ch) . "'\n";
-// test version info
echo "\n--- version ---\n";
$ver = curl_version();
echo "has version: " . (isset($ver['version']) ? 'yes' : 'no') . "\n";
echo "has ssl: " . (isset($ver['ssl_version']) ? 'yes' : 'no') . "\n";
-// test method routing with match
echo "\n--- method routing ---\n";
$methods = [HttpMethod::GET, HttpMethod::POST, HttpMethod::PUT, HttpMethod::DELETE, HttpMethod::PATCH];
foreach ($methods as $method) {
diff --git a/examples/image-thumbnail/main.php b/examples/image-thumbnail/main.php
index 13930f27..a75c146d 100644
--- a/examples/image-thumbnail/main.php
+++ b/examples/image-thumbnail/main.php
@@ -1,7 +1,4 @@
value yield),
-// generator methods (current, key, valid, next, getReturn), Fiber (start,
-// resume, suspend, getReturn, isTerminated), iterator chaining, generator
-// delegation, generator exception handling, closures as generator factories,
-// foreach on generators, generator state lifecycle
-// --- fiber basics ---
echo "=== Fiber Basics ===\n";
@@ -23,7 +17,6 @@
echo "return: " . $fiber->getReturn() . "\n";
echo "terminated: " . ($fiber->isTerminated() ? 'yes' : 'no') . "\n";
-// --- fiber as coroutine ---
echo "\n=== Fiber Coroutine ===\n";
@@ -51,7 +44,6 @@ function make_counter(int $start): Fiber {
$counter->resume('stop');
echo "terminated: " . ($counter->isTerminated() ? 'yes' : 'no') . "\n";
-// --- multiple fibers interleaved ---
echo "\n=== Interleaved Fibers ===\n";
@@ -99,7 +91,6 @@ function make_worker(string $name, int $steps): Fiber {
echo "$entry\n";
}
-// --- basic generator pipeline ---
echo "\n=== Generator Pipeline ===\n";
@@ -143,7 +134,6 @@ function take_gen(Generator $source, int $n): Generator {
}
echo "pipeline: " . implode(', ', $results) . "\n";
-// --- key-value yield ---
echo "\n=== Key-Value Yield ===\n";
@@ -178,7 +168,6 @@ function sum_gen(array $nums): Generator {
echo "running sums: " . implode(', ', $running) . "\n";
echo "final return: " . $gen->getReturn() . "\n";
-// --- generator send ---
echo "\n=== Generator Send ===\n";
@@ -200,7 +189,6 @@ function accumulator(): Generator {
$result = $acc->send(null);
echo "accumulated: " . $acc->getReturn() . "\n";
-// --- generator state methods ---
echo "\n=== Generator State ===\n";
@@ -221,7 +209,6 @@ function three_items(): Generator {
$gen->next();
echo "exhausted valid: " . ($gen->valid() ? 'yes' : 'no') . "\n";
-// --- generator factory closures ---
echo "\n=== Generator Factory ===\n";
@@ -241,7 +228,6 @@ function make_repeater(string $value, int $times): Closure {
}
echo "repeated: " . implode(', ', $items) . "\n";
-// --- chained generator transforms ---
echo "\n=== Chained Transforms ===\n";
@@ -278,7 +264,6 @@ function flatten_gen(Generator $source): Generator {
}
echo "chunk-flatten-double: " . implode(', ', $results) . "\n";
-// --- generator with exception ---
echo "\n=== Generator Exception ===\n";
@@ -302,7 +287,6 @@ function safe_divide_gen(array $pairs): Generator {
}
echo implode(', ', $results) . "\n";
-// --- yield from delegation ---
echo "\n=== Yield From ===\n";
@@ -325,7 +309,6 @@ function outer_gen(): Generator {
}
echo "all items: " . implode(', ', $items) . "\n";
-// --- nested yield from ---
echo "\n=== Nested Yield From ===\n";
@@ -394,7 +377,6 @@ function select(Generator $source, string $field): Generator {
}
echo "engineering: " . implode(', ', $eng) . "\n";
-// --- fiber with generator ---
echo "\n=== Fiber With Generator ===\n";
diff --git a/examples/job-queue/main.php b/examples/job-queue/main.php
index 0daa6382..f80a5882 100644
--- a/examples/job-queue/main.php
+++ b/examples/job-queue/main.php
@@ -1,8 +1,6 @@
), preg_match_all PREG_SET_ORDER, generators with send(), priority queue insertion, exception handling in generators
error_reporting(E_ALL & ~E_DEPRECATED);
-// DSL parser with named regex
function parseJobDef(string $line): ?array {
$pattern = '/^(?P ' . parseInline($line) . '
';
continue;
}
- // blockquote
if (str_starts_with($line, '>')) {
if (!$inBlockquote) {
$html[] = '';
@@ -74,7 +66,6 @@ function parseMarkdown(string $markdown): string {
continue;
}
- // unordered list
if (preg_match('/^\s*[-*]\s+(.+)$/', $line, $matches)) {
if (!$inList || $listType !== 'ul') {
if ($inList) $html[] = '';
@@ -86,7 +77,6 @@ function parseMarkdown(string $markdown): string {
continue;
}
- // ordered list
if (preg_match('/^\s*\d+\.\s+(.+)$/', $line, $matches)) {
if (!$inList || $listType !== 'ol') {
if ($inList) $html[] = '';
@@ -98,7 +88,6 @@ function parseMarkdown(string $markdown): string {
continue;
}
- // paragraph
$html[] = '
$1', $text);
- // links
$text = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '$1', $text);
- // images
$text = preg_replace('/!\[([^\]]*)\]\(([^)]+)\)/', '', $text);
return $text;
}
-// --- test ---
$markdown = <<<'MD'
# Markdown Parser
@@ -176,7 +158,6 @@ function hello() {
$html = parseMarkdown($markdown);
echo $html . "\n";
-// --- verify specific patterns ---
echo "\nInline parsing:\n";
$tests = [
diff --git a/examples/math-crypto/main.php b/examples/math-crypto/main.php
index 7eb0bb8e..0d4b9e62 100644
--- a/examples/math-crypto/main.php
+++ b/examples/math-crypto/main.php
@@ -1,11 +1,5 @@
1e308: " . (PHP_FLOAT_MAX > 1e308 ? 'yes' : 'no') . "\n";
-// --- hash functions ---
echo "\n=== Hash Functions ===\n";
@@ -91,7 +79,6 @@
echo "hash('md5', 'hello'): " . hash('md5', 'hello') . "\n";
echo "crc32('hello'): " . crc32('hello') . "\n";
-// --- hmac ---
echo "\n=== HMAC ===\n";
@@ -99,7 +86,6 @@
echo "hash_hmac('md5', 'data', 'key'): " . hash_hmac('md5', 'data', 'key') . "\n";
echo "hash_hmac('sha1', 'data', 'key'): " . hash_hmac('sha1', 'data', 'key') . "\n";
-// --- password hashing ---
echo "\n=== Password Hashing ===\n";
@@ -109,7 +95,6 @@
echo "verify correct: " . (password_verify('secret123', $hash) ? 'yes' : 'no') . "\n";
echo "verify wrong: " . (password_verify('wrong', $hash) ? 'yes' : 'no') . "\n";
-// --- random ---
echo "\n=== Random ===\n";
@@ -119,7 +104,6 @@
echo "random_bytes length: " . strlen($bytes) . "\n";
echo "random_bytes hex length: " . strlen(bin2hex($bytes)) . "\n";
-// --- numeric checks ---
echo "\n=== Numeric Checks ===\n";
@@ -134,7 +118,6 @@
echo "is_numeric(true): " . (is_numeric(true) ? 'yes' : 'no') . "\n";
echo "is_numeric(null): " . (is_numeric(null) ? 'yes' : 'no') . "\n";
-// --- type conversion ---
echo "\n=== Type Conversion ===\n";
@@ -145,7 +128,6 @@
echo "floatval('3.14'): " . floatval('3.14') . "\n";
echo "floatval('1.2e3'): " . floatval('1.2e3') . "\n";
-// --- sprintf with numbers ---
echo "\n=== Sprintf ===\n";
@@ -159,7 +141,6 @@
echo sprintf("percent: %%") . "\n";
echo sprintf("multiple: %d + %d = %d", 2, 3, 5) . "\n";
-// --- array math ---
echo "\n=== Array Math ===\n";
diff --git a/examples/math-edge-cases/main.php b/examples/math-edge-cases/main.php
index a77484d0..e6d00816 100644
--- a/examples/math-edge-cases/main.php
+++ b/examples/math-edge-cases/main.php
@@ -1,10 +1,5 @@
0 ? "true" : "false") . "\n";
-// --- float precision ---
echo "--- float precision ---\n";
echo "0.1 + 0.2 == 0.3: " . ((0.1 + 0.2) == 0.3 ? "true" : "false") . "\n";
@@ -24,7 +18,6 @@
echo "1/3 + 2/3: " . (1/3 + 2/3) . "\n";
echo "1/3 * 3: " . (1/3 * 3) . "\n";
-// --- division ---
echo "--- division ---\n";
echo "10 / 3: " . (10 / 3) . "\n";
@@ -33,7 +26,6 @@
echo "-7 / 2: " . (-7 / 2) . "\n";
echo "intdiv(-7, 2): " . intdiv(-7, 2) . "\n";
-// --- modulo ---
echo "--- modulo ---\n";
echo "10 % 3: " . (10 % 3) . "\n";
@@ -43,7 +35,6 @@
echo "fmod(10.5, 3.2): " . fmod(10.5, 3.2) . "\n";
echo "fmod(-10.5, 3.2): " . fmod(-10.5, 3.2) . "\n";
-// --- special values ---
echo "--- special values ---\n";
echo "INF: " . INF . "\n";
@@ -60,7 +51,6 @@
echo "INF * 0: " . (INF * 0) . "\n";
echo "1 / INF: " . (1 / INF) . "\n";
-// --- math functions ---
echo "--- math functions ---\n";
echo "abs(-42): " . abs(-42) . "\n";
@@ -87,7 +77,6 @@
echo "log10(1000): " . log10(1000) . "\n";
echo "log2(8): " . log(8, 2) . "\n";
-// --- type conversion ---
echo "--- type conversion ---\n";
echo "intval('42'): " . intval('42') . "\n";
@@ -98,7 +87,6 @@
echo "intval(3.9): " . intval(3.9) . "\n";
echo "intval(-3.9): " . intval(-3.9) . "\n";
-// --- bitwise ---
echo "--- bitwise ---\n";
echo "0xFF & 0x0F: " . (0xFF & 0x0F) . "\n";
@@ -108,7 +96,6 @@
echo "1 << 8: " . (1 << 8) . "\n";
echo "256 >> 4: " . (256 >> 4) . "\n";
-// --- comparison edge cases ---
echo "--- comparisons ---\n";
echo "0 == false: " . (0 == false ? "true" : "false") . "\n";
@@ -119,7 +106,6 @@
echo "0 == null: " . (0 == null ? "true" : "false") . "\n";
echo "'' == null: " . ('' == null ? "true" : "false") . "\n";
-// spaceship operator
echo "1 <=> 2: " . (1 <=> 2) . "\n";
echo "2 <=> 1: " . (2 <=> 1) . "\n";
echo "1 <=> 1: " . (1 <=> 1) . "\n";
diff --git a/examples/math-precision/main.php b/examples/math-precision/main.php
index 9d3e4bea..70112515 100644
--- a/examples/math-precision/main.php
+++ b/examples/math-precision/main.php
@@ -1,9 +1,5 @@
10 = " . base_convert('73', 36, 10) . "\n";
-// color math with hex
echo "\n=== color math ===\n";
function hexToRgb(string $hex): array {
$hex = ltrim($hex, '#');
@@ -76,7 +69,6 @@ function blendColors(string $c1, string $c2, float $ratio): string {
echo sprintf(" %.0f%%: %s\n", $r * 100, blendColors($red, $blue, $r));
}
-// logarithms and scientific calculations
echo "\n=== logarithms ===\n";
$values = [1, 2, 10, 100, 1024, 65536];
echo sprintf(" %-8s %8s %8s %8s\n", "value", "log2", "log10", "ln");
@@ -84,7 +76,6 @@ function blendColors(string $c1, string $c2, float $ratio): string {
echo sprintf(" %-8d %8.4f %8.4f %8.4f\n", $v, log($v) / log(2), log10($v), log($v));
}
-// pythagorean calculations with hypot
echo "\n=== hypot (pythagorean) ===\n";
$triangles = [[3, 4], [5, 12], [8, 15], [7, 24]];
foreach ($triangles as $t) {
@@ -92,7 +83,6 @@ function blendColors(string $c1, string $c2, float $ratio): string {
echo sprintf(" sides %2d, %2d -> hypotenuse = %.4f\n", $t[0], $t[1], $h);
}
-// distance between 2D points
function distance(float $x1, float $y1, float $x2, float $y2): float {
return hypot($x2 - $x1, $y2 - $y1);
}
@@ -104,7 +94,6 @@ function distance(float $x1, float $y1, float $x2, float $y2): float {
echo sprintf(" (%.0f,%.0f) to (%.0f,%.0f) = %.4f\n", $p[0], $p[1], $p[2], $p[3], $d);
}
-// rounding modes
echo "\n=== rounding ===\n";
$nums = [2.5, 3.5, 4.5, -2.5, 2.55, 2.449];
echo sprintf(" %-8s %8s %8s %8s %8s\n", "value", "round", "floor", "ceil", "round2");
@@ -113,7 +102,6 @@ function distance(float $x1, float $y1, float $x2, float $y2): float {
$n, round($n), floor($n), ceil($n), round($n, 1));
}
-// financial calculations with number_format
echo "\n=== financial formatting ===\n";
$prices = [1234.5, 1000000, 0.99, 42195.876, 0.001];
foreach ($prices as $price) {
@@ -122,7 +110,6 @@ function distance(float $x1, float $y1, float $x2, float $y2): float {
number_format($price, 2, '.', ','));
}
-// fmod for precise remainder
echo "\n=== fmod ===\n";
$fmod_cases = [[10.5, 3.2], [2.5, 0.5], [7.0, 2.5], [-5.5, 3.0]];
foreach ($fmod_cases as $case) {
diff --git a/examples/matrix-math/main.php b/examples/matrix-math/main.php
index 74e9356f..dfb6c66c 100644
--- a/examples/matrix-math/main.php
+++ b/examples/matrix-math/main.php
@@ -1,5 +1,4 @@
setHeader("X-Request-ID", "req-12345");
@@ -88,7 +84,6 @@ function addRequestId(Request $req, callable $next): Response
return $response;
}
-// middleware: log
$log = [];
function logMiddleware(Request $req, callable $next): Response
{
@@ -99,7 +94,6 @@ function logMiddleware(Request $req, callable $next): Response
return $response;
}
-// middleware: auth check
function authMiddleware(Request $req, callable $next): Response
{
$token = $req->getHeader("Authorization");
@@ -110,14 +104,12 @@ function authMiddleware(Request $req, callable $next): Response
return $next($req);
}
-// final handler
function handler(Request $req): Response
{
$resp = new Response();
return $resp->setStatus(200)->setBody("Hello from " . $req->path);
}
-// test 1: request with auth
$pipeline = new Pipeline();
$pipeline->pipe("addRequestId")
->pipe("logMiddleware")
@@ -138,7 +130,6 @@ function handler(Request $req): Response
echo "status: " . $resp2->status . "\n";
echo "body: " . $resp2->body . "\n";
-// log output
foreach ($log as $entry) {
echo "log: " . $entry . "\n";
}
diff --git a/examples/mime-encoder/main.php b/examples/mime-encoder/main.php
index 130fedb0..07c2e866 100644
--- a/examples/mime-encoder/main.php
+++ b/examples/mime-encoder/main.php
@@ -1,7 +1,5 @@
", false) . "\n";
-// --- str_word_count ---
echo "\nWord count:\n";
$sentence = "Hello beautiful world";
@@ -64,13 +55,11 @@
$words = str_word_count("The quick brown fox", 1);
echo "Word list: " . implode(", ", $words) . "\n";
-// mode 2: return positions
$positions = str_word_count("Hello world test", 2);
foreach ($positions as $pos => $word) {
echo " Position $pos: $word\n";
}
-// --- array_combine ---
echo "\nArray combine:\n";
$keys = ['name', 'age', 'city'];
@@ -80,7 +69,6 @@
echo " $k: $v\n";
}
-// --- array_flip ---
echo "\nArray flip:\n";
$colors = ['red' => 1, 'green' => 2, 'blue' => 3];
@@ -89,12 +77,10 @@
echo " $k => $v\n";
}
-// flip indexed array
$fruits = ['apple', 'banana', 'cherry'];
$fruit_index = array_flip($fruits);
echo "Index of banana: " . $fruit_index['banana'] . "\n";
-// --- array_pad ---
echo "\nArray pad:\n";
$arr = [1, 2, 3];
@@ -107,7 +93,6 @@
$no_pad = array_pad($arr, 2, 0);
echo "Pad to 2 (no change): " . implode(",", $no_pad) . "\n";
-// --- MIME header encoding ---
echo "\nMIME header encoding:\n";
@@ -193,7 +178,6 @@ function buildMimeMessage(array $parts): string {
echo "Has boundary: " . (str_contains($message, "----boundary_12345") ? "yes" : "no") . "\n";
echo "Has base64: " . (str_contains($message, "Content-Transfer-Encoding: base64") ? "yes" : "no") . "\n";
-// decode the attachment back
preg_match('/Content-Transfer-Encoding: base64\r\n.+?\r\n\r\n(.+?)(?:\r\n\r\n--|\z)/s', $message, $matches);
if (isset($matches[1])) {
$decoded_attachment = base64_decode(trim($matches[1]));
@@ -268,7 +252,6 @@ function formatTable(array $rows, int $cols): void {
['Size'],
], 2);
-// --- word frequency analysis ---
echo "\nWord frequency:\n";
$text = "the cat sat on the mat the cat";
diff --git a/examples/mini-shell/main.php b/examples/mini-shell/main.php
index 39a77e8f..06a421eb 100644
--- a/examples/mini-shell/main.php
+++ b/examples/mini-shell/main.php
@@ -1,12 +1,5 @@
$h) {
$headerCells[] = str_pad($h, $widths[$i]);
}
$lines[] = implode(' | ', $headerCells);
- // separator
$sepCells = [];
foreach ($widths as $w) {
$sepCells[] = str_repeat('-', $w);
}
$lines[] = implode('-+-', $sepCells);
- // rows
foreach ($rows as $row) {
$cells = [];
foreach ($row as $i => $cell) {
@@ -237,7 +223,6 @@ function formatTable($headers, $rows) {
]
) . "\n";
-// --- glob pattern matching ---
function globMatch($pattern, $string) {
$regex = '/^';
@@ -269,7 +254,6 @@ function globMatch($pattern, $string) {
echo "test?.log matches test12.log: " . (globMatch('test?.log', 'test12.log') ? 'yes' : 'no') . "\n";
echo "*.* matches any.file: " . (globMatch('*.*', 'any.file') ? 'yes' : 'no') . "\n";
-// --- number formatting ---
echo "--- numbers ---\n";
echo number_format(1234567.89, 2) . "\n";
@@ -277,7 +261,6 @@ function globMatch($pattern, $string) {
echo number_format(1000000, 0, '.', ',') . "\n";
echo number_format(0.5, 4) . "\n";
-// --- array operations ---
echo "--- array ops ---\n";
diff --git a/examples/multi-file/main.php b/examples/multi-file/main.php
index 470e9955..866b942c 100644
--- a/examples/multi-file/main.php
+++ b/examples/multi-file/main.php
@@ -1,11 +1,4 @@
[
@@ -57,17 +49,14 @@
echo "first user: {$decoded['users'][0]['name']}\n";
echo "meta total: {$decoded['meta']['total']}\n";
-// nested json with special chars
$special = ['message' => 'hello "world" &