@@ -79,3 +79,56 @@ pub fn throw_exception() -> PhpResult<i32> {
79
79
# }
80
80
# fn main() {}
81
81
```
82
+
83
+ ## Implementing an Interface
84
+
85
+ To implement an interface, use ` #[implements(ce)] ` where ` ce ` is an expression returning a ` ClassEntry ` .
86
+ The following example implements [ ` ArrayAccess ` ] ( https://www.php.net/manual/en/class.arrayaccess.php ) :
87
+ ``` rust,no_run
88
+ # #![cfg_attr(windows, feature(abi_vectorcall))]
89
+ # extern crate ext_php_rs;
90
+ use ext_php_rs::prelude::*;
91
+ use ext_php_rs::{exception::PhpResult, types::Zval, zend::ce};
92
+
93
+ #[php_class]
94
+ #[implements(ce::arrayaccess())]
95
+ #[derive(Default)]
96
+ pub struct EvenNumbersArray;
97
+
98
+ /// Returns `true` if the array offset is an even number.
99
+ /// Usage:
100
+ /// ```php
101
+ /// $arr = new EvenNumbersArray();
102
+ /// var_dump($arr[0]); // true
103
+ /// var_dump($arr[1]); // false
104
+ /// var_dump($arr[2]); // true
105
+ /// var_dump($arr[3]); // false
106
+ /// var_dump($arr[4]); // true
107
+ /// var_dump($arr[5] = true); // Fatal error: Uncaught Exception: Setting values is not supported
108
+ /// ```
109
+ #[php_impl]
110
+ impl EvenNumbersArray {
111
+ pub fn __construct() -> EvenNumbersArray {
112
+ EvenNumbersArray {}
113
+ }
114
+ // We need to use `Zval` because ArrayAccess needs $offset to be a `mixed`
115
+ pub fn offset_exists(&self, offset: &'_ Zval) -> bool {
116
+ offset.is_long()
117
+ }
118
+ pub fn offset_get(&self, offset: &'_ Zval) -> PhpResult<bool> {
119
+ let integer_offset = offset.long().ok_or("Expected integer offset")?;
120
+ Ok(integer_offset % 2 == 0)
121
+ }
122
+ pub fn offset_set(&mut self, _offset: &'_ Zval, _value: &'_ Zval) -> PhpResult {
123
+ Err("Setting values is not supported".into())
124
+ }
125
+ pub fn offset_unset(&mut self, _offset: &'_ Zval) -> PhpResult {
126
+ Err("Setting values is not supported".into())
127
+ }
128
+ }
129
+ # #[php_module]
130
+ # pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
131
+ # module
132
+ # }
133
+ # fn main() {}
134
+ ```
0 commit comments