PHP Reference ยท Functions and Classes
PHP method_exists() and property_exists()
Reference for method_exists() and property_exists(): checking class members, private and static members, magic methods and the is_callable() alternative.
method_exists() tells you whether a class or object has a method with a given name, and property_exists() does the same for properties. Both accept either an object or a class name string, and both look at declarations, not at what the calling code is allowed to access.
They are handy before calling a method named by data (a callback from configuration, a hook name from a plugin), but they only answer "is it declared", so combine them with is_callable() when visibility matters.
method_exists(object|string $objectOrClass, string $method): bool property_exists(object|string $objectOrClass, string $property): bool
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
method_exists(object|string $objectOrClass, string $method): bool property_exists(object|string $objectOrClass, string $property): bool
| Name | Description |
|---|---|
$objectOrClass |
An object, or a class name string (autoloading is attempted for strings). |
$method / $property |
The member name. Method names are case-insensitive; property names are case-sensitive. |
Return value: true if declared, otherwise false. An unknown class name also gives false.
Usage notes
- Visibility is ignored. Private and protected members count, so
truedoes not mean you can call or read the member from your scope. method_exists()ignores__call(). A class that handles any name through__callstill returnsfalsefor names it does not declare.is_callable()honours__calland visibility.property_exists()is true for declared properties even if unset or uninitialized.isset()isfalsefor anullvalue and for an uninitialized typed property. For dynamic properties on an object,property_exists($object, ...)istrueonly while they exist; with the class name it isfalse.__get()is not considered. Virtual values that come only from magic methods are not found.- Static members are found by both functions.
- For callbacks,
is_callable([$object, 'name'])is usually the right test;method_exists()is for "does the class have this API". isset($object->prop)answers a different question (is it set and notnull).array_key_exists()no longer accepts objects (removed in PHP 8.0).- Reflection (
ReflectionClass::hasMethod()) gives the same information plus details.