Skip to content

Instantly share code, notes, and snippets.

@flavioheleno
Created January 14, 2022 15:27
Show Gist options
  • Save flavioheleno/db631c062af07f8c87a7525b35e60461 to your computer and use it in GitHub Desktop.
Save flavioheleno/db631c062af07f8c87a7525b35e60461 to your computer and use it in GitHub Desktop.
How do I..?

How do I..?

Contents

...

Class

Define a Class

Userland (src/class.php)

src/class.h

src/class.c

Define Class Methods

Userland (src/class.php)

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

hdi.stub.php

class Hdi {
  public function sayHello(): string {}
}

class_arginfo.h

/* This is a generated file, edit the .stub.php file instead. */
/* NOTE: Only relevant code below! */
ZEND_METHOD(Hdi, sayHello);

static const zend_function_entry class_Hdi_methods[] = {
  ZEND_ME(Hdi, sayHello, arginfo_class_Hdi_sayHello, ZEND_ACC_PUBLIC) /* visibility: public */
  ZEND_FE_END
};

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Hdi_sayHello, 0, 0, IS_STRING, 0) /* return type: string */
ZEND_END_ARG_INFO()

Macros and Functions:

Visibility options:

Type options:

src/class.c

/* {{{ Hdi: function sayHello(): string */
PHP_METHOD(Hdi, sayHello) {
  ZEND_PARSE_PARAMETERS_NONE();

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

Macros and Functions:

Class Properties

Define

Userland (src/class.php)

private string $name;

src/class.c

  zval propDefaultValue;
  zend_string *propName;
  /* default property value (undefined) */
  ZVAL_UNDEF(&propDefaultValue);

  propName = zend_string_init("name", sizeof("name") - 1, false); /* $name */
  zend_declare_typed_property(
    classEntry,
    propName,
    &propDefaultValue,
    ZEND_ACC_PRIVATE, /* visibility: private */
    NULL,
    (zend_type)ZEND_TYPE_INIT_MASK(MAY_BE_STRING) /* type: string */
  );
  zend_string_release(propName);

Macros and Functions:

Visibility options:

Type options:

Language Reference

Core Reference

Set Property Value

src/class.c

zend_update_property_string(classEntry, Z_OBJ_P(ZEND_THIS), "name", sizeof("name") - 1, "name");

Macros and Functions:

Read Property Value

src/class.c

zval rv;
zval *name = zend_read_property(classEntry, Z_OBJ_P(ZEND_THIS), "name", sizeof("name") - 1, true, &rv);

Macros and Functions:

Define Class Constants

Language Reference

Define an Interface

Language Reference

Implement an Interface

Define an Abstract Class

Language Reference

Inherit from a Class

Language Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment