Class Methods

This chapter covers how to define a class method.

Note that details such as method arguments and method return values are covered in the functions chapter.

Code sample for this chapter, with additional examples, is available here.

Userland PHP Code Snippet

The code below shows how a class method would be declared and implemented in userland PHP code.

class Hdi {
  public function sayHello(): string {
    return 'Hello World!';
  }
}

Internal PHP Code

The following sections show all required code to declare and implement a class method internally in PHP.

PHP Stub (hdi.stub.php)

The stub file is used to declare the method signature:

  • visibility (public)
  • name (sayHello)
  • argument list (())
  • return type (string)
class Hdi {
  public function sayHello(): string {}
}

Argument Information (hdi_arginfo.h)

This file is generated during compilation, based on the stub file contents.

The argument information header is the standard/default file where all class methods details are defined:

  • declaration (ZEND_METHOD)
    • class name (Hdi)
    • method name (sayHello)
  • class method list (class_Hdi_methods[] variable)
    • entry registration (ZEND_ME)
      • class name (Hdi)
      • method name (sayHello)
      • argument information (arginfo_class_Hdi_sayHello)
      • visibility (ZEND_ACC_PUBLIC)
  • argument declaration (ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX)
    • argument information name (arginfo_class_Hdi_sayHello)
    • return reference (0 ie. return by value)
    • required arguments (0 ie. no required arguments)
    • return type (IS_STRING)
    • allow null (0 ie. not allowed)
/* This is a generated file, edit the .stub.php file instead. */
/* NOTE: Only relevant code is shown below! */
ZEND_METHOD(Hdi, sayHello);

static const zend_function_entry class_Hdi_methods[] = {
  ZEND_ME(Hdi, sayHello, arginfo_class_Hdi_sayHello, ZEND_ACC_PUBLIC)
  ZEND_FE_END
};

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Hdi_sayHello, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()

Macros and Functions:

Visibility options:

Type options:

Implementation (hdi.c)

The implementation below is quite simple and straight forward:

  • declaration (PHP_METHOD)
    • class name (Hdi)
    • method name (sayHello)
  • parameter parsing (ZEND_PARSE_PARAMETERS_NONE)
  • return (RETURN_STR)
    • value string ("Hello World!")
/* {{{ Hdi: function sayHello(): string */
PHP_METHOD(Hdi, sayHello) {
  ZEND_PARSE_PARAMETERS_NONE();

  RETURN_STR("Hello World!");
}
/* }}} */

Macros and Functions:


Copyright (c) 2022 - Flavio Heleno