# `#[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.
- `no_constructor` - A class without a constructor declares none, rather than one
that throws: `new` creates an object initialized with `Default::default()`. The
struct must implement `Default`. See [Constructors](./impl.md#constructors).
- `#[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`.
- Generated stubs write each parent class and interface name as a fully qualified
name, with a leading `\`. A leading `\` in `stub = "..."` is optional.
You may also use the `#[php(prop)]` attribute on a struct field to use the field as a
PHP property. By default, the property is public and its name is the field name
converted to camelCase: the field `first_name` gives the property `firstName`.
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)]`
### How PHP code uses a Rust property
The value of a `#[php(prop)]` field is in the Rust struct. PHP reads the value
with the getter and writes the value with the setter.
These operations use the getter and the setter:
- `$obj->prop += 1`, `$obj->prop .= 'x'`, `$obj->prop++` and `$obj->prop ??= 1`.
- `==` and `foreach`, which use the current Rust values. Thus `==` calls each
getter of the two objects.
These operations change only a copy, and the Rust value does not change:
- `$obj->prop[] = 1`, `$obj->prop['key'] = 1` and `$r = &$obj->prop`. PHP gives
the notice "Indirect modification of overloaded property", as for `__get`.
- `foreach ($obj as &$value)`.
These operations throw an `Error`:
- `$obj->prop = &$value`.
- `unset($obj->prop)`, because the Rust value cannot be removed.
If a PHP subclass declares the property again with hooks, PHP uses the Rust
getter and setter, not the hooks.
### Typed properties
A property PHP stores itself, rather than in the Rust struct, can be declared
with a type, as `protected int $count = 0;` declares one in PHP. Add it with
`ClassBuilder::typed_property` from the class's `modifier` function: the engine
enforces the type on every write (coercing in weak mode), reflection reports it,
and without a default the property starts uninitialized. PHP subclasses read and
write it like any declared property.
```rust,ignore
use ext_php_rs::builders::{ClassBuilder, ClassProperty};
use ext_php_rs::flags::{DataType, PropertyFlags};
use ext_php_rs::prelude::*;
use ext_php_rs::types::Zval;
#[php_class]
#[php(modifier = counter_properties)]
pub struct Counter;
fn counter_properties(builder: ClassBuilder) -> ClassBuilder {
builder.typed_property(ClassProperty {
name: "count".into(),
flags: PropertyFlags::Protected,
default: Some(Box::new(|| {
let mut zero = Zval::new();
zero.set_long(0);
Ok(zero)
})),
docs: &[],
ty: Some(DataType::Long),
nullable: false,
readonly: false,
default_stub: Some("0".into()),
})
}
```
A property type is `bool`, `int`, `float`, `string`, `array`, `object`, `mixed`
or a class, nullable or not; `iterable`, `resource`, `callable` and the other
`DataType`s are refused. A default must be a value of the type (an `int`
default of a `float` property becomes a float). Readonly typed properties, and
typed properties of a readonly class, are not supported yet. Registration fails
with `Error::InvalidPropertyType` otherwise.
`ClassBuilder::property` declares a property without a type; its `ty` only
shapes the generated stubs.
## Access to the Rust Value
The object keeps its Rust value in a borrow cell. Each method borrows the value
until the method returns:
- A `&self` method borrows the value as shared. Other `&self` methods and
property reads can use the value at the same time.
- A `&mut self` method borrows the value as exclusive. No other method and no
other property access can use the value at the same time.
A method can call PHP code, for example a callback. That PHP code can call a
method on the same object. If the second call conflicts with the borrow, PHP
throws an `Error`:
| A `&self` method or a property read while a `&mut self` method runs | `Cannot use object of class Foo while one of its methods modifies it` |
| A `&mut self` method or a property write while a different method runs | `Cannot modify object of class Foo while it is in use` |
| The object has no Rust value, for example a subclass that does not call `parent::__construct()` | `Object of class Foo is not initialized` |
### Class Arguments
A parameter of a `#[php_class]` type borrows the Rust value of the object:
- `&Foo` gives shared access to the value.
- `&mut Foo` gives exclusive access to the value.
- `Option<&Foo>` and `Option<&mut Foo>` also accept `null`.
The borrow starts before the function body and stops when the function returns.
The rules of [Access to the Rust Value](#access-to-the-rust-value) apply during
the call. If two parameters, or the object of the method and a parameter, get
the same object and the borrows conflict, PHP throws an `Error`.
The borrow guards `ClassRef<Foo>` and `ClassRefMut<Foo>` are also parameter
types. A variadic parameter must use them, for example `&[ClassRef<Foo>]`. The
value parameter of a property setter accepts the same types.
Only a `#[php_class]` type can be a class parameter. The PHP objects of a
`#[php_enum]` type hold no Rust value, so a `&Suit` parameter does not compile.
Take the enum by value, for example `suit: Suit`.
A PHP fatal error during the call stops the function without the release of the
borrow. The object stays borrowed until the end of the request.
```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::prelude::*;
#[php_class]
pub struct Counter {
count: i64,
}
#[php_function]
pub fn add_to(target: &mut Counter, source: &Counter) -> i64 {
target.count += source.count;
target.count
}
#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
module.class::<Counter>().function(wrap_function!(add_to))
}
# fn main() {}
```
### Class Objects in a `Zval`
`Zval::extract::<ClassRef<Foo>>()` gives `None` if the value is not a `Foo`.
It also gives `None` if a method of the object borrows the Rust value. To know
the cause, use `Zval::try_extract`:
- `Error::ZvalConversion` tells that the value is not a `Foo`.
- `Error::Borrow` tells that the borrow conflicts with a method of the object.
```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{error::Error, prelude::*, types::Zval};
#[php_class]
pub struct Counter {
count: i64,
}
#[php_function]
pub fn count_of(value: &Zval) -> PhpResult<Option<i64>> {
match value.try_extract::<ClassRef<Counter>>() {
Ok(counter) => Ok(Some(counter.count)),
Err(Error::ZvalConversion(_)) => Ok(None),
Err(err) => Err(err.into()),
}
}
#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
module.class::<Counter>().function(wrap_function!(count_of))
}
# fn main() {}
```
### Call PHP Code from a Method
A `&mut self` method keeps the exclusive borrow until it returns. If a PHP
callback of the method calls a method on the same object, the callback gets an
`Error`. To let the callback use the object, use `self_: &ZendClassObject<Self>`
in place of `&mut self`. Then borrow the value only when it is necessary:
```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{
prelude::*,
types::{ZendClassObject, Zval},
};
#[php_class]
pub struct EventEmitter {
listeners: Vec<Zval>,
}
#[php_impl]
impl EventEmitter {
pub fn __construct() -> Self {
Self {
listeners: Vec::new(),
}
}
pub fn on(&mut self, listener: &Zval) {
self.listeners.push(listener.shallow_clone());
}
pub fn emit(self_: &ZendClassObject<Self>) -> PhpResult<()> {
let listeners: Vec<Zval> = self_
.try_borrow()?
.listeners
.iter()
.map(Zval::shallow_clone)
.collect();
for listener in &listeners {
listener.try_call(vec![])?;
}
Ok(())
}
}
#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
module.class::<EventEmitter>()
}
# fn main() {}
```
The guard of `try_borrow()` stops at the end of the `let` statement. Thus a
listener can call `$emitter->on()` during `emit()`.
## PHP Values in Rust Fields
A field can keep a PHP value, for example a callback. Two objects that refer to
each other make a cycle. The PHP cycle collector finds and frees each cycle that
no other value refers to. The collector must know the values that each object
keeps.
`#[php_class]` gives the collector the value of each field that has one of
these types:
- `Zval`.
- `ZBox<ZendObject>` and `ZBox<ZendClassObject<T>>`.
- `ZendCallable` when it owns its value.
- `Option`, `Box`, `Vec` and arrays of these types, and the values of a
`HashMap` or a `BTreeMap` of these types.
You do not write code for these fields. In this example, the collector frees the
emitter and the closure after `unset($emitter)`:
```rust,no_run
# #![cfg_attr(windows, feature(abi_vectorcall))]
# extern crate ext_php_rs;
use ext_php_rs::{prelude::*, types::Zval};
#[php_class]
pub struct EventEmitter {
listeners: Vec<Zval>,
}
#[php_impl]
impl EventEmitter {
pub fn __construct() -> Self {
Self {
listeners: Vec::new(),
}
}
pub fn on(&mut self, listener: &Zval) {
self.listeners.push(listener.shallow_clone());
}
}
#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
module.class::<EventEmitter>()
}
# fn main() {}
```
```php
$emitter = new EventEmitter();
$emitter->on(fn() => $emitter);
unset($emitter);
gc_collect_cycles();
```
While a `&mut self` method runs, the collector does not read the Rust fields
of the object. The collector then counts the values of these fields as used
from outside the cycle. A later collection frees the cycle.
The collector does not see the values in other types, for example
`ZBox<ZendHashTable>`, `Rc`, `Arc`, `RefCell` and Rust closures. A cycle through
these fields stays in memory until the end of the request. To let the collector
see a PHP array, keep the array in a `Zval`.
For a field of your own type, implement the unsafe trait `GcTrace` for the type.
The implementation must give only the PHP values that the type owns, and each
value one time. If it gives a value two times, the collector can free a value
that is in use. Do not give the values in a `RefCell`, a `Cell` or a `Mutex`.
A shared borrow does not stop a change of these values.
```rust,no_run
# extern crate ext_php_rs;
use ext_php_rs::{
gc::{GcRoots, GcTrace},
types::Zval,
};
pub struct Listener {
name: String,
callback: Zval,
}
unsafe impl GcTrace for Listener {
unsafe fn gc_trace(&self, roots: &mut GcRoots) {
// SAFETY: `callback` is the only PHP value of `Listener`.
unsafe { self.callback.gc_trace(roots) };
}
}
# fn main() {}
```
## 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 for the PHP versions (Php80, Php81, Php82, etc.). It is `#[non_exhaustive]`, so a `match` on it must have a `_` arm.
- `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
implement `Clone`. A derive or a hand-written `impl Clone` both work, and the
spelling of the derive path does not matter. The cloned PHP object contains a
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
```
The clone of a PHP subclass has the class of the subclass. PHP copies the
properties of the subclass and calls its `__clone` method.
A class whose struct does not implement `Clone` has no clone handler, like the
uncloneable classes of PHP. `clone` throws an `Error` that names the class of
the object, and `ReflectionClass::isCloneable()` returns `false`:
```php
// If MyClass does not implement Clone:
$obj = new MyClass();
$copy = clone $obj; // Error: Trying to clone an uncloneable object of class MyClass
```
A `clone` of an object that one of its methods modifies at that time throws an
`Error`. A `clone` of an object that has no Rust value, for example a PHP
subclass that did not call the parent constructor, also throws an `Error`.
When a clone fails, PHP does not call `__destruct` on the failed copy.
A `__clone` method does not make a class cloneable. If the struct does not
implement `Clone`, `clone` throws, but `ReflectionClass::isCloneable()`
returns `true` because PHP sees the `__clone` method.
## 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
```