Skip to content

Commit a331213

Browse files
authored
Add instance_of() and get_class_entry() methods on ZendObject (#197)
* adds `ZendObject::get_class_entry()` to retrieve the class entry of an object without casting pointers * adds `ZendObject::instance_of()` to allow more idiomatic instanceof checks. * adds a mention that `ZendObject::is_instance::<T>()` does not check the parent classes or interfaces. This bit me when I tried to check if `my_object.is_instance::<MyInterface>()` and it didn't work.
1 parent 580ad9f commit a331213

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/types/object.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,17 @@ impl ZendObject {
8080
unsafe { ZBox::from_raw(this.get_mut_zend_obj()) }
8181
}
8282

83+
/// Returns the [`ClassEntry`] associated with this object.
84+
///
85+
/// # Panics
86+
///
87+
/// Panics if the class entry is invalid.
88+
pub fn get_class_entry(&self) -> &'static ClassEntry {
89+
// SAFETY: it is OK to panic here since PHP would segfault anyway
90+
// when encountering an object with no class entry.
91+
unsafe { self.ce.as_ref() }.expect("Could not retrieve class entry.")
92+
}
93+
8394
/// Attempts to retrieve the class name of the object.
8495
pub fn get_class_name(&self) -> Result<String> {
8596
unsafe {
@@ -91,8 +102,21 @@ impl ZendObject {
91102
}
92103
}
93104

105+
/// Returns whether this object is an instance of the given [`ClassEntry`].
106+
///
107+
/// This method checks the class and interface inheritance chain.
108+
///
109+
/// # Panics
110+
///
111+
/// Panics if the class entry is invalid.
112+
pub fn instance_of(&self, ce: &ClassEntry) -> bool {
113+
self.get_class_entry().instance_of(ce)
114+
}
115+
94116
/// Checks if the given object is an instance of a registered class with
95117
/// Rust type `T`.
118+
///
119+
/// This method doesn't check the class and interface inheritance chain.
96120
pub fn is_instance<T: RegisteredClass>(&self) -> bool {
97121
(self.ce as *const ClassEntry).eq(&(T::get_metadata().ce() as *const _))
98122
}

0 commit comments

Comments
 (0)