Skip to content

Commit 580ad9f

Browse files
authored
Describes restrictions on generic parameters for php_class (#194)
1 parent 3d74226 commit 580ad9f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

guide/src/macros/classes.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,34 @@ You can rename the property with options:
3232
- `rename` - Allows you to rename the property, e.g.
3333
`#[prop(rename = "new_name")]`
3434

35+
## Restrictions
36+
37+
### No lifetime parameters
38+
39+
Rust lifetimes are used by the Rust compiler to reason about a program's memory safety.
40+
They are a compile-time only concept;
41+
there is no way to access Rust lifetimes at runtime from a dynamic language like PHP.
42+
43+
As soon as Rust data is exposed to PHP,
44+
there is no guarantee which the Rust compiler can make on how long the data will live.
45+
PHP is a reference-counted language and those references can be held
46+
for an arbitrarily long time, which is untraceable by the Rust compiler.
47+
The only possible way to express this correctly is to require that any `#[php_class]`
48+
does not borrow data for any lifetime shorter than the `'static` lifetime,
49+
i.e. the `#[php_class]` cannot have any lifetime parameters.
50+
51+
When you need to share ownership of data between PHP and Rust,
52+
instead of using borrowed references with lifetimes, consider using
53+
reference-counted smart pointers such as [Arc](https://doc.rust-lang.org/std/sync/struct.Arc.html).
54+
55+
### No generic parameters
56+
57+
A Rust struct `Foo<T>` with a generic parameter `T` generates new compiled implementations
58+
each time it is used with a different concrete type for `T`.
59+
These new implementations are generated by the compiler at each usage site.
60+
This is incompatible with wrapping `Foo` in PHP,
61+
where there needs to be a single compiled implementation of `Foo` which is integrated with the PHP interpreter.
62+
3563
## Example
3664

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

0 commit comments

Comments
 (0)