Unlock Strong Typing in PHP with Swoole’s Typed Array: Guide, Limits & Benchmarks
This article explains how Swoole introduces a typed array feature to PHP, covering its API, supported type definitions, usage restrictions, type‑checking methods, performance comparison with native arrays, and instructions for building the extension, helping developers achieve stricter type safety in backend code.
Overview
PHP’s dynamic weak‑type system can lead to type‑related bugs in large codebases. Swoole introduced a typed_array implementation that adds strong‑type support for arrays, completing PHP’s type system.
Usage
The core constructor is typed_array() with the following prototype:
function typed_array(string $typeDef, ?array $initValues = null): array {} $typeDefdefines the allowed element types and can describe nested structures. Supported type tokens are: int, float, bool, null, resource, array, string,
object list– homogeneous list, e.g.
<string> map– key/value map, e.g. <int, string> (key must be int, value string) key – only int or string are allowed as keys $initValues may be an existing typed array (reference‑counted) or a plain PHP array. When a plain array is supplied, each element is validated against the type definition; a mismatch throws a TypeError.
List restrictions
Typed arrays declared as list forbid random deletions or insertions. Use array_splice() to remove elements, or array_unshift() / array_splice() to insert at the beginning or middle.
Object and class support
Custom class names can be used as type tokens. The runtime checks with instanceof and throws a TypeError if an object of a different class is inserted.
Multi‑dimensional arrays
Typed arrays support unlimited nesting, e.g.
<int, <string, <int, <string, string>>>>is valid.
Type verification
Typed arrays provide an isTyped() method to check whether a variable is a typed array and optionally verify its definition: function isTyped(string $typeDef = ''): bool {} If $typeDef is omitted, the method only confirms the variable is a typed array.
When a definition is supplied, the method returns true only if the array matches it.
Assignment and copy‑on‑write
Assigning one typed array to another of the same type increments the reference count without copying data. Modifying either array triggers copy‑on‑write, creating a new underlying array.
Performance test
The following benchmark inserts one million string elements into a typed array and a native array:
$tarr = typed_array('<string>');
$arr = array();
$s = microtime(true);
$n = 100_0000;
while ($n--) {
$tarr[] = str_repeat('A', 256);
// $arr[] = str_repeat('A', 256);
}
echo "taken seconds: ".(microtime(true)-$s)."
";Test result:
typed array: taken seconds: 0.75667595863342
array: taken seconds: 0.5811140537262The typed array’s write speed is about 28 % slower than a native array, a reasonable trade‑off for strict type safety.
Compilation and build
The feature resides in the swoole stdext module, which has not yet been merged into the main branch. To try it early, clone the swoole-src repository and build the stdext branch manually:
git clone https://github.com/swoole/swoole-src.git
cd swoole-src
git checkout stdext
# Follow the standard Swoole build steps (phpize, ./configure, make, make install)Conclusion
Typed array support fills the last gap in PHP’s type system, enabling stronger compile‑time guarantees, reducing runtime errors, and lowering the risk of large‑scale refactoring. The modest performance overhead is outweighed by the gains in code reliability for backend development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
