ext-php-rs 0.15.10

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
# `#[php_class]` Attribute

Structs can be exported to PHP as classes with the `#[php_class]` attribute
macro. This attribute derives the `RegisteredClass` trait on your struct, as
well as registering the class to be registered with the `#[php_module]` macro.

## Options

There are additional macros that modify the class. These macros **must** be
placed underneath the `#[php_class]` attribute.

- `name` - Changes the name of the class when exported to PHP. The Rust struct
  name is kept the same. If no name is given, the name of the struct is used.
  Useful for namespacing classes.
- `change_case` - Changes the case of the class name when exported to PHP.
- `readonly` - Marks the class as readonly (PHP 8.2+). All properties in a
  readonly class are implicitly readonly.
- `flags` - Sets class flags using `ClassFlags`, e.g.
  `#[php(flags = ClassFlags::Final)]` for a final class.
- `#[php(extends(...))]` - Sets the parent class of the class. Can only be used once.
  Two forms are supported:
  - Simple type form: `#[php(extends(MyBaseClass))]` - For Rust-defined classes that implement `RegisteredClass`.
  - Explicit form: `#[php(extends(ce = ce_fn, stub = "ParentClass"))]` - For built-in PHP classes.
    `ce_fn` must be a function with the signature `fn() -> &'static ClassEntry`.
- `#[php(implements(...))]` - Implements the given interface on the class. Can be used multiple times.
  Two forms are supported:
  - Simple type form: `#[php(implements(MyInterface))]` — For Rust-defined interfaces that implement `RegisteredClass`.
  - Explicit form: `#[php(implements(ce = ce_fn, stub = "InterfaceName"))]` — For built-in PHP interfaces.
    `ce_fn` must be a valid function with the signature `fn() -> &'static ClassEntry`.

You may also use the `#[php(prop)]` attribute on a struct field to use the field as a
PHP property. By default, the field will be accessible from PHP publicly with
the same name as the field. Property types must implement `IntoZval` and
`FromZval`.

You can customize properties with these options:

- `name` - Allows you to rename the property, e.g.
  `#[php(prop, name = "new_name")]`
- `change_case` - Allows you to rename the property using rename rules, e.g.
  `#[php(prop, change_case = PascalCase)]`
- `static` - Makes the property static (shared across all instances), e.g.
  `#[php(prop, static)]`
- `flags` - Sets property visibility flags, e.g.
  `#[php(prop, flags = ext_php_rs::flags::PropertyFlags::Private)]`

## Restrictions

### No lifetime parameters

Rust lifetimes are used by the Rust compiler to reason about a program's memory safety.
They are a compile-time only concept;
there is no way to access Rust lifetimes at runtime from a dynamic language like PHP.

As soon as Rust data is exposed to PHP,
there is no guarantee which the Rust compiler can make on how long the data will live.
PHP is a reference-counted language and those references can be held
for an arbitrarily long time, which is untraceable by the Rust compiler.
The only possible way to express this correctly is to require that any `#[php_class]`
does not borrow data for any lifetime shorter than the `'static` lifetime,
i.e. the `#[php_class]` cannot have any lifetime parameters.

When you need to share ownership of data between PHP and Rust,
instead of using borrowed references with lifetimes, consider using
reference-counted smart pointers such as [Arc](https://doc.rust-lang.org/std/sync/struct.Arc.html).

### No generic parameters

A Rust struct `Foo<T>` with a generic parameter `T` generates new compiled implementations
each time it is used with a different concrete type for `T`.
These new implementations are generated by the compiler at each usage site.
This is incompatible with wrapping `Foo` in PHP,
where there needs to be a single compiled implementation of `Foo` which is integrated with the PHP interpreter.

## Example

This example creates a PHP class `Human`, adding a PHP property `address`.

```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;

#[php_class]
pub struct Human {
    name: String,
    age: i32,
    #[php(prop)]
    address: String,
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.class::<Human>()
}
# fn main() {}
```

Create a custom exception `RedisException`, which extends `Exception`, and put
it in the `Redis\Exception` namespace:

```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{
    prelude::*,
    exception::PhpException,
    zend::ce
};

#[php_class]
#[php(name = "Redis\\Exception\\RedisException")]
#[php(extends(ce = ce::exception, stub = "\\Exception"))]
#[derive(Default)]
pub struct RedisException;

// Throw our newly created exception
#[php_function]
pub fn throw_exception() -> PhpResult<i32> {
    Err(PhpException::from_class::<RedisException>("Not good!".into()))
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .class::<RedisException>()
        .function(wrap_function!(throw_exception))
}
# fn main() {}
```

### Extending a Rust-defined Class

When extending another Rust-defined class, you can use the simpler type syntax:

```rust,ignore
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;

#[php_class]
#[derive(Default)]
pub struct Animal;

#[php_impl]
impl Animal {
    pub fn speak(&self) -> &'static str {
        "..."
    }
}

#[php_class]
#[php(extends(Animal))]
#[derive(Default)]
pub struct Dog;

#[php_impl]
impl Dog {
    pub fn speak(&self) -> &'static str {
        "Woof!"
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .class::<Animal>()
        .class::<Dog>()
}
# fn main() {}
```

#### Sharing Methods Between Parent and Child Classes

When both parent and child are Rust-defined classes, methods defined only in the parent
won't automatically work when called on a child instance. This is because each Rust type
has its own object handlers.

The recommended workaround is to use a Rust trait for shared behavior:

```rust,ignore
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;

/// Trait for shared behavior
trait AnimalBehavior {
    fn speak(&self) -> &'static str {
        "..."
    }
}

#[php_class]
#[derive(Default)]
pub struct Animal;

impl AnimalBehavior for Animal {}

#[php_impl]
impl Animal {
    pub fn speak(&self) -> &'static str {
        AnimalBehavior::speak(self)
    }
}

#[php_class]
#[php(extends(Animal))]
#[derive(Default)]
pub struct Dog;

impl AnimalBehavior for Dog {
    fn speak(&self) -> &'static str {
        "Woof!"
    }
}

#[php_impl]
impl Dog {
    // Re-export the method so it works on Dog instances
    pub fn speak(&self) -> &'static str {
        AnimalBehavior::speak(self)
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module
        .class::<Animal>()
        .class::<Dog>()
}
# fn main() {}
```

This pattern ensures that:
- `$animal->speak()` returns `"..."`
- `$dog->speak()` returns `"Woof!"`
- `$dog instanceof Animal` is `true`

## Implementing an Interface

To implement an interface, use `#[php(implements(...))]`. For built-in PHP interfaces, use the explicit form with `ce` and `stub`. For Rust-defined interfaces, you can use the simple type form.
The following example implements [`ArrayAccess`](https://www.php.net/manual/en/class.arrayaccess.php):

````rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{
    prelude::*,
    exception::PhpResult,
    types::Zval,
    zend::ce,
};

#[php_class]
#[php(implements(ce = ce::arrayaccess, stub = "\\ArrayAccess"))]
#[derive(Default)]
pub struct EvenNumbersArray;

/// Returns `true` if the array offset is an even number.
/// Usage:
/// ```php
/// $arr = new EvenNumbersArray();
/// var_dump($arr[0]); // true
/// var_dump($arr[1]); // false
/// var_dump($arr[2]); // true
/// var_dump($arr[3]); // false
/// var_dump($arr[4]); // true
/// var_dump($arr[5] = true); // Fatal error:  Uncaught Exception: Setting values is not supported
/// ```
#[php_impl]
impl EvenNumbersArray {
    pub fn __construct() -> EvenNumbersArray {
        EvenNumbersArray {}
    }
    // We need to use `Zval` because ArrayAccess needs $offset to be a `mixed`
    pub fn offset_exists(&self, offset: &'_ Zval) -> bool {
        offset.is_long()
    }
    pub fn offset_get(&self, offset: &'_ Zval) -> PhpResult<bool> {
        let integer_offset = offset.long().ok_or("Expected integer offset")?;
        Ok(integer_offset % 2 == 0)
    }
    pub fn offset_set(&mut self, _offset: &'_ Zval, _value: &'_ Zval) -> PhpResult {
        Err("Setting values is not supported".into())
    }
    pub fn offset_unset(&mut self, _offset: &'_ Zval) -> PhpResult {
        Err("Setting values is not supported".into())
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.class::<EvenNumbersArray>()
}
# fn main() {}
````

## Static Properties

Static properties are shared across all instances of a class. Use `#[php(prop, static)]`
to declare a static property. Unlike instance properties, static properties are managed
entirely by PHP and do not use Rust property handlers.

You can specify a default value using the `default` attribute:

```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;
use ext_php_rs::class::RegisteredClass;

#[php_class]
pub struct Counter {
    #[php(prop)]
    pub instance_value: i32,
    #[php(prop, static, default = 0)]
    pub count: i32,
    #[php(prop, static, flags = ext_php_rs::flags::PropertyFlags::Private)]
    pub internal_state: String,
}

#[php_impl]
impl Counter {
    pub fn __construct(value: i32) -> Self {
        Self {
            instance_value: value,
            count: 0,
            internal_state: String::new(),
        }
    }

    /// Increment the static counter from Rust
    pub fn increment() {
        let ce = Self::get_metadata().ce();
        let current: i64 = ce.get_static_property("count").unwrap_or(0);
        ce.set_static_property("count", current + 1).unwrap();
    }

    /// Get the current count
    pub fn get_count() -> i64 {
        let ce = Self::get_metadata().ce();
        ce.get_static_property("count").unwrap_or(0)
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.class::<Counter>()
}
# fn main() {}
```

From PHP, you can access static properties directly on the class:

```php
// No need to initialize - count already has default value of 0
Counter::increment();
Counter::increment();
echo Counter::$count; // 2
echo Counter::getCount(); // 2
```

## Abstract Classes

Abstract classes cannot be instantiated directly and may contain abstract methods
that must be implemented by subclasses. Use `#[php(flags = ClassFlags::Abstract)]`
to declare an abstract class:

```rust,ignore
use ext_php_rs::prelude::*;
use ext_php_rs::flags::ClassFlags;

#[php_class]
#[php(flags = ClassFlags::Abstract)]
pub struct AbstractAnimal;

#[php_impl]
impl AbstractAnimal {
    // Protected constructor for subclasses
    #[php(vis = "protected")]
    pub fn __construct() -> Self {
        Self
    }

    // Abstract method - must be implemented by subclasses.
    // Body is never called; use unimplemented!() as a placeholder.
    #[php(abstract)]
    pub fn speak(&self) -> String {
        unimplemented!()
    }

    // Concrete method - inherited by subclasses
    pub fn breathe(&self) {
        println!("Breathing...");
    }
}
```

From PHP, you can extend this abstract class:

```php
class Dog extends AbstractAnimal {
    public function __construct() {
        parent::__construct();
    }

    public function speak(): string {
        return "Woof!";
    }
}

$dog = new Dog();
echo $dog->speak(); // "Woof!"
$dog->breathe();    // "Breathing..."

// This would cause an error:
// $animal = new AbstractAnimal(); // Cannot instantiate abstract class
```

See the [impl documentation](./impl.md#abstract-methods) for more details on
abstract methods.

## Final Classes

Final classes cannot be extended. Use `#[php(flags = ClassFlags::Final)]` to
declare a final class:

```rust,ignore
use ext_php_rs::prelude::*;
use ext_php_rs::flags::ClassFlags;

#[php_class]
#[php(flags = ClassFlags::Final)]
pub struct FinalClass;
```

## Readonly Classes (PHP 8.2+)

PHP 8.2 introduced [readonly classes](https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.readonly),
where all properties are implicitly readonly. You can create a readonly class using
the `#[php(readonly)]` attribute:

```rust,ignore
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;

#[php_class]
#[php(readonly)]
pub struct ImmutablePoint {
    x: f64,
    y: f64,
}

#[php_impl]
impl ImmutablePoint {
    pub fn __construct(x: f64, y: f64) -> Self {
        Self { x, y }
    }

    pub fn get_x(&self) -> f64 {
        self.x
    }

    pub fn get_y(&self) -> f64 {
        self.y
    }

    pub fn distance_from_origin(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.class::<ImmutablePoint>()
}
# fn main() {}
```

From PHP:

```php
$point = new ImmutablePoint(3.0, 4.0);
echo $point->getX(); // 3.0
echo $point->getY(); // 4.0
echo $point->distanceFromOrigin(); // 5.0

// On PHP 8.2+, you can verify the class is readonly:
$reflection = new ReflectionClass(ImmutablePoint::class);
var_dump($reflection->isReadOnly()); // true
```

The `readonly` attribute is compatible with other class attributes:

```rust,ignore
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;
use ext_php_rs::flags::ClassFlags;

// Readonly + Final class
#[php_class]
#[php(readonly)]
#[php(flags = ClassFlags::Final)]
pub struct FinalImmutableData {
    value: String,
}
# fn main() {}
```

**Note:** The `readonly` attribute requires PHP 8.2 or later. Using it when
compiling against an earlier PHP version will result in a compile error.

### Conditional Compilation for Multi-Version Support

If your extension needs to support both PHP 8.1 and PHP 8.2+, you can use
conditional compilation to only enable readonly on supported versions.

First, add `ext-php-rs-build` as a build dependency in your `Cargo.toml`:

```toml
[build-dependencies]
ext-php-rs-build = "0.1"
anyhow = "1"
```

Then create a `build.rs` that detects the PHP version and emits cfg flags:

```rust,ignore
use ext_php_rs_build::{find_php, PHPInfo, ApiVersion, emit_php_cfg_flags, emit_check_cfg};

fn main() -> anyhow::Result<()> {
    let php = find_php()?;
    let info = PHPInfo::get(&php)?;
    let version: ApiVersion = info.zend_version()?.try_into()?;

    emit_check_cfg();
    emit_php_cfg_flags(version);
    Ok(())
}
```

Now you can use `#[cfg(php82)]` to conditionally apply the readonly attribute:

```rust,ignore
#[php_class]
#[cfg_attr(php82, php(readonly))]
pub struct MaybeReadonlyClass {
    value: String,
}
```

The `ext-php-rs-build` crate provides several useful utilities:

- `find_php()` - Locates the PHP executable (respects the `PHP` env var)
- `PHPInfo::get()` - Runs `php -i` and parses the output
- `ApiVersion` - Enum representing PHP versions (Php80, Php81, Php82, etc.)
- `emit_php_cfg_flags()` - Emits `cargo:rustc-cfg=phpXX` for all supported versions
- `emit_check_cfg()` - Emits check-cfg to avoid unknown cfg warnings

This is **optional** - if your extension only targets PHP 8.2+, you can use
`#[php(readonly)]` directly without any build script setup.

## Cloning

PHP's native `clone` operator is supported for `#[php_class]` structs that
derive `Clone`. Add `#[derive(Clone)]` to your struct and the cloned PHP object
will contain a proper copy of the Rust data:

```rust,ignore
use ext_php_rs::prelude::*;

#[php_class]
#[derive(Clone)]
pub struct Style {
    #[php(prop)]
    pub font_size: f64,
    #[php(prop)]
    pub color: String,
}

#[php_impl]
impl Style {
    pub fn __construct(font_size: f64, color: String) -> Self {
        Self { font_size, color }
    }
}
```

```php
$style = new Style(12.0, 'red');
$copy = clone $style;

$copy->fontSize = 16.0;
echo $style->fontSize;  // 12.0 — original is unchanged
```

Structs that do **not** derive `Clone` will throw an error when cloned:

```php
// If MyClass doesn't #[derive(Clone)]:
$obj = new MyClass();
$copy = clone $obj; // Error: Trying to clone an uncloneable object of class MyClass
```

## Implementing Iterator

To make a Rust class usable with PHP's `foreach` loop, implement the
[`Iterator`](https://www.php.net/manual/en/class.iterator.php) interface.
This requires implementing five methods: `current()`, `key()`, `next()`, `rewind()`, and `valid()`.

The following example creates a `RangeIterator` that iterates over a range of integers:

````rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{prelude::*, zend::ce};

#[php_class]
#[php(implements(ce = ce::iterator, stub = "\\Iterator"))]
pub struct RangeIterator {
    start: i64,
    end: i64,
    current: i64,
    index: i64,
}

#[php_impl]
impl RangeIterator {
    /// Create a new range iterator from start to end (inclusive).
    pub fn __construct(start: i64, end: i64) -> Self {
        Self {
            start,
            end,
            current: start,
            index: 0,
        }
    }

    /// Return the current element.
    pub fn current(&self) -> i64 {
        self.current
    }

    /// Return the key of the current element.
    pub fn key(&self) -> i64 {
        self.index
    }

    /// Move forward to next element.
    pub fn next(&mut self) {
        self.current += 1;
        self.index += 1;
    }

    /// Rewind the Iterator to the first element.
    pub fn rewind(&mut self) {
        self.current = self.start;
        self.index = 0;
    }

    /// Checks if current position is valid.
    pub fn valid(&self) -> bool {
        self.current <= self.end
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.class::<RangeIterator>()
}
# fn main() {}
````

Using the iterator in PHP:

```php
<?php

$range = new RangeIterator(1, 5);

// Use with foreach
foreach ($range as $key => $value) {
    echo "$key => $value\n";
}
// Output:
// 0 => 1
// 1 => 2
// 2 => 3
// 3 => 4
// 4 => 5

// Works with iterator functions
$arr = iterator_to_array(new RangeIterator(10, 12));
// [0 => 10, 1 => 11, 2 => 12]

$count = iterator_count(new RangeIterator(1, 100));
// 100
```

### Iterator with Mixed Types

You can return different types for keys and values. The following example uses string keys:

````rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{prelude::*, zend::ce};

#[php_class]
#[php(implements(ce = ce::iterator, stub = "\\Iterator"))]
pub struct MapIterator {
    keys: Vec<String>,
    values: Vec<String>,
    index: usize,
}

#[php_impl]
impl MapIterator {
    pub fn __construct() -> Self {
        Self {
            keys: vec!["first".into(), "second".into(), "third".into()],
            values: vec!["one".into(), "two".into(), "three".into()],
            index: 0,
        }
    }

    pub fn current(&self) -> Option<String> {
        self.values.get(self.index).cloned()
    }

    pub fn key(&self) -> Option<String> {
        self.keys.get(self.index).cloned()
    }

    pub fn next(&mut self) {
        self.index += 1;
    }

    pub fn rewind(&mut self) {
        self.index = 0;
    }

    pub fn valid(&self) -> bool {
        self.index < self.keys.len()
    }
}

#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
    module.class::<MapIterator>()
}
# fn main() {}
````

```php
<?php

$map = new MapIterator();
foreach ($map as $key => $value) {
    echo "$key => $value\n";
}
// Output:
// first => one
// second => two
// third => three
```