# `#[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
```
