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:

  1. 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.

  2. $obj = new MyClass(): We instantiate an object of the MyClass class to get its methods.

  3. $methods = get_class_methods($obj): This line retrieves the array of method names and stores it in the $methods variable.

  4. foreach ($methods as $method): A foreach loop is used to iterate over the array of method names.

  5. 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:

  1. Create a class and define its methods.
  2. Instantiate an object of that class.
  3. Call get_class_methods() on the object to retrieve an array of method names.
  4. 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