Attribute Macro ext_php_rs::php_class [−][src]
#[php_class]
Expand description
Annotates a struct that will be exported to PHP as a class.
The struct that this attribute is used on must implement Default
, as this is used to
initialize the struct before the constructor is called. You may define a constructor with
the php_impl
macro which can modify the properties of the struct.
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, andce
may be any valid expression.#[implements(ce)]
- Implements an interface on the new class. Can be used multiple times, andce
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]
#[derive(Default)]
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::php::exceptions::PhpException;
use ext_php_rs::php::class::ClassEntry;
#[php_class(name = "Redis\\Exception\\RedisException")]
#[extends(ClassEntry::exception())]
#[derive(Default)]
pub struct Example;
#[php_function]
pub fn throw_exception() -> Result<i32, PhpException<'static>> {
Err(PhpException::from_class::<Example>("Bad things happen".into()))
}
#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
module
}