Class Constants
This chapter covers how to define a class constant.
Note that more in dept details about constants are covered in the constants chapter.
Code sample for this chapter, with additional examples, is available here.
Userland PHP Code Snippet
The code below shows how a class constant would be declared in userland PHP code.
class Hdi {
public const HELLO = 'World!';
}
Internal PHP Code
The following sections show all required code to declare and implement a class constant internally in PHP.
PHP Stub (hdi.stub.php
)
The stub file should not declare class constants as the stub generator script (gen_stub.php) cannot handle it at this moment.
Argument Information (hdi_arginfo.h
)
Class constants are not referred to nor registered in the argument information file, so it can be skipped.
Implementation (hdi.c
)
The implementation below is a little bit more elaborate than what is seen in global scope constant, but it can be broken into:
- name definition (
zend_string_init
)- name string (
"HELLO"
) - name size (
sizeof
) - persistent string (
0
ie. not persistent1)
- name string (
- value definition (
ZVAL_NEW_STR
andzend_string_init
)- value string (
"World!"
) - value size (
sizeof
) - persistent string (depends if
classEntry->type
is aZEND_INTERNAL_CLASS
or not)
- value string (
- declaration (
zend_declare_class_constant_ex
)- class entry (
classEntry
) - visibility (
ZEND_ACC_PRIVATE
)
- class entry (
zend_string *name = zend_string_init(
"HELLO",
sizeof("HELLO") - 1,
0
);
zval value;
ZVAL_NEW_STR(
&value,
zend_string_init(
"World!",
sizeof("World!") - 1,
classEntry->type & ZEND_INTERNAL_CLASS
)
);
zend_declare_class_constant_ex(
classEntry,
name,
&value,
ZEND_ACC_PRIVATE,
NULL
);
zend_string_release(name);
Alternatively, for public class constants, it can be simplified as:
zend_declare_class_constant_string(
classEntry,
"HELLO",
sizeof("HELLO") - 1,
"World!"
);
Macros and Functions:
- zend_string_init
- ZVAL_NEW_STR
- zend_declare_class_constant_ex
- zend_string_release
- zend_declare_class_constant_string
Visibility options:
Notes:
More about persistent objects in the Zend Memory Manager chapter of the PHP Internals Book.
Copyright (c) 2022 - Flavio Heleno