PHP for getting the class methods of an object
Code Solution:
class MyClass {
public function method1() {}
public function method2() {}
protected function method3() {}
private function method4() {}
}
$obj = new MyClass();
$methods = get_class_methods($obj);
foreach ($methods as $method) {
echo $method . "\n";
}
Explanation:
-
get_class_methods(): This function takes an object as an argument and returns an array of all the method names implemented by that object. It includes both public and protected methods, but not private methods.
-
$obj = new MyClass(): We instantiate an object of the
MyClass
class to get its methods. -
$methods = get_class_methods($obj): This line retrieves the array of method names and stores it in the
$methods
variable. -
foreach ($methods as $method): A
foreach
loop is used to iterate over the array of method names. -
echo $method . "\n": Inside the loop, each method name is printed to the console, followed by a newline character.
Implementation:
To use this code effectively, follow these steps:
- Create a class and define its methods.
- Instantiate an object of that class.
- Call
get_class_methods()
on the object to retrieve an array of method names. - Iterate over the array to get individual method names.
This code is useful for various purposes, such as:
- Introspection of object methods
- Generating API documentation
- Dynamically accessing methods based on user input
- Extending classes through dynamic method invocation