Attribute Macro ext_php_rs::php_class[][src]

#[php_class]
Expand description

Annotates a struct that will be exported to PHP as a class.

By default, the class cannot be constructed from PHP. You must add a constructor method in the php_impl impl block to be able to construct the object from PHP.

This attribute takes a set of optional arguments:

  • name - The name of the exported class, if it is different from the Rust struct name. This can be useful for namespaced classes, as you cannot place backslashes in Rust struct names.

Any struct that uses this attribute can also provide an optional set of extra attributes, used to modify the class. These attributes must be used underneath this attribute, as they are not valid Rust attributes, and instead are parsed by this attribute:

  • #[extends(ce)] - Sets the parent class of this new class. Can only be used once, and ce may be any valid expression.
  • #[implements(ce)] - Implements an interface on the new class. Can be used multiple times, and ce may be any valid expression.

This attribute (and its associated structs) must be defined above the startup function (which is annotated by the php_startup macro, or automatically generated just above the php_module function).

Fields defined on the struct are not the same as PHP properties, and are only accessible from Rust.

Example

Export a simple class called Example, with 3 Rust fields.

#[php_class]
pub struct Example {
    x: i32,
    y: String,
    z: bool
}

#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module
}

Create a custom exception RedisException inside the namespace Redis\Exception:

use ext_php_rs::exception::PhpException;
use ext_php_rs::zend::ce;

#[php_class(name = "Redis\\Exception\\RedisException")]
#[extends(ce::exception())]
pub struct Example;

#[php_function]
pub fn throw_exception() -> Result<i32, PhpException> {
    Err(PhpException::from_class::<Example>("Bad things happen".into()))
}

#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module
}