Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 295 lines (227 sloc) 12.781 kb
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
1 PHP Coding Standards
2 ====================
3
4
5 This file lists several standards that any programmer, adding or changing
6 code in PHP, should follow. Since this file was added at a very late
7 stage of the development of PHP v3.0, the code base does not (yet) fully
45807e6 Jon Parise Added a brief section documenting the preference of tabs over spaces.
jparise authored
8 follow it, but it's going in that general direction. Since we are now
9 well into the version 4 releases, many sections have been recoded to use
10 these rules.
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
11
12
13 Code Implementation
14 -------------------
15
6d10159 comments & php_error_docref
Marcus Boerger authored
16 [0] Document your code in source files and the manual. [tm]
17
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
18 [1] Functions that are given pointers to resources should not free them
19
20 For instance, function int mail(char *to, char *from) should NOT free
21 to and/or from.
22 Exceptions:
23
24 - The function's designated behavior is freeing that resource. E.g. efree()
25 - The function is given a boolean argument, that controls whether or not
26 the function may free its arguments (if true - the function must free its
27 arguments, if false - it must not)
28 - Low-level parser routines, that are tightly integrated with the token
29 cache and the bison code for minimum memory copying overhead.
30
31 [2] Functions that are tightly integrated with other functions within the
32 same module, and rely on each other non-trivial behavior, should be
33 documented as such and declared 'static'. They should be avoided if
34 possible.
35
36 [3] Use definitions and macros whenever possible, so that constants have
37 meaningful names and can be easily manipulated. The only exceptions
38 to this rule are 0 and 1, when used as false and true (respectively).
39 Any other use of a numeric constant to specify different behavior
40 or actions should be done through a #define.
41
42 [4] When writing functions that deal with strings, be sure to remember
43 that PHP holds the length property of each string, and that it
44 shouldn't be calculated with strlen(). Write your functions in a such
45 a way so that they'll take advantage of the length property, both
46 for efficiency and in order for them to be binary-safe.
47 Functions that change strings and obtain their new lengths while
48 doing so, should return that new length, so it doesn't have to be
585e338 php4ize a bit.
Sterling Hughes authored
49 recalculated with strlen() (e.g. php_addslashes())
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
50
6d10159 comments & php_error_docref
Marcus Boerger authored
51 [5] Use php_error_docref() group of functions to report any errors/warnings
52 during code execution. Use descriptive error messages, and try to avoid
53 using identical error strings for different stages of an error. For
54 example, if in order to obtain a URL you have to parse the URL, connect,
55 and retreive the text, assuming something can go wrong at each of these
56 stages, don't report an error "Unable to get URL" on all of them, but
57 instead, write something like "Unable to parse URL", "Unable to connect
58 to URL server" and "Unable to fetch URL text", respectively.
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
59
652baa7 - Add note how php_error() messages SHOULD (rfc2119) look like.
Markus Fischer authored
60 It has been silently agreed to prefix every php_error() message with the
61 name of the current function if applicable:
62
63 php_error(E_WHATEVER, "%s(): Desc.", get_active_function_name(TSRMLS_C));
64
6d10159 comments & php_error_docref
Marcus Boerger authored
65 This can be done automatically using php_error_docref(). The first
66 parameter, docref, is either NULL or the URL of a page describing the
0a84571 -better use external example
Marcus Boerger authored
67 error in detail. In most cases you will pass NULL, to generate the URL
68 from the name of the function being executed:
6d10159 comments & php_error_docref
Marcus Boerger authored
69
70 php_error_docref(NULL TSRMLS_CC, E_WHATEVER, "Desc.");
71
72 If you pass a URL, it can either be a full URL beginning with "http://":
73
0a84571 -better use external example
Marcus Boerger authored
74 php_error_docref("http://externalsite.tld/page.ext#error"
6d10159 comments & php_error_docref
Marcus Boerger authored
75 TSRMLS_CC, E_WHATEVER, "Desc.");
76
77 Or the name of a manual page without file extension, but with an optional
78 target anchor. Or simply the anchor within the manual page of the current
79 function. When using function names you must replace '_' by '-':
80
0a84571 -better use external example
Marcus Boerger authored
81 php_error_docref("function.ext-func#error" TSRMLS_CC, E_WHATEVER, "Desc.");
6d10159 comments & php_error_docref
Marcus Boerger authored
82
83 To display one or two important parameters after the function name, use
84 php_error_docref1() or php_error_docref2(). For example, file functions
85 should display the name of the file opened:
86
6ce08f7 fix examples
Marcus Boerger authored
87 php_error_docref1("function.fopen" TSRMLS_CC, filename,
88 E_WHATEVER, "Desc.");
6d10159 comments & php_error_docref
Marcus Boerger authored
89
6ce08f7 fix examples
Marcus Boerger authored
90 php_error_docref2("function.fopen" TSRMLS_CC, filename, openmode,
91 E_WHATEVER, "Desc.");
6d10159 comments & php_error_docref
Marcus Boerger authored
92
652baa7 - Add note how php_error() messages SHOULD (rfc2119) look like.
Markus Fischer authored
93 Fixing ("unifying") existing php_error() message is a good thing [tm].
94
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
95 [6] NEVER USE strncat(). If you're absolutely sure you know what you're doing,
96 check its man page again, and only then, consider using it, and even then,
97 try avoiding it.
98
8e7147a - Use PHP_ instead of ZEND_
Derick Rethans authored
99 [7] Use PHP_* macros in the PHP source, and ZEND_* macros in the Zend
612d5b9 - spaces instead of tabs
Derick Rethans authored
100 part of the source. Although the PHP_* macro's are mostly aliased to the
101 ZEND_* macros it gives a better understanding on what kind of macro you're
102 calling.
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
103
86dba96 Translate to English.
Sean Bright authored
104 [8] Use assert(). assert.h is included in php.h if it is available. Not only
105 does good assertion catch bugs, but it also helps with code readability.
69d6f1e Added README.SUBMITTING_PATCH file. Please fix/add/change.
Yasuo Ohgaki authored
106 - Do not use assert for error handling. Use assert only for the
107 condition that must be always true.
108 - Do not use assignments in assert conditions. If you assign inside an
109 assert condition, you risk an elusive bug that would be very difficult
110 to spot in a debug build, due to the side effect of the assignment.
111 Function calls in assert conditions may also cause this problem, if
112 they modify one of their arguments or global variables.
cbc1cd8 Include/enable assert.h/assert() when it is available
Yasuo Ohgaki authored
113
2e6d771 As per the suggestion on php-dev, now please #ifdef 0_<username here>
Dan Kalowsky authored
114 [9] When commenting out code using a #if statement, do NOT use 0 only. Append
115 to any 0 an _<cvs username here>. For example, #if 0_FOO, where FOO is
116 cvs user foo. This allows easier tracking of why code was commented out,
117 especially in bundled libraries.
118
d6b4462 Jon Parise Reword item 10 for greater clarity.
jparise authored
119 [10] Do not define functions that are not available. For instance, if a
120 library is missing a function, do not define the PHP version of the
121 function, and do not raise a run-time error about the function not
122 existing. End users should use function_exists() to test for the
123 existence of a function
ab0da7d It seems we're better to mention about missing functions.
Yasuo Ohgaki authored
124
e79772d Jon Parise Adding a new item (number 11) that explains why it's important to use
jparise authored
125 [11] Prefer emalloc(), efree(), estrdup(), etc. to their standard C library
126 counterparts. These functions implement an internal "safety-net"
127 mechanism that ensures the deallocation of any unfreed memory at the
128 end of a request. They also provide useful allocation and overflow
129 information while running in debug mode.
130
131 In almost all cases, memory returned to the engine must be allocated
132 using emalloc().
133
134 The use of malloc() should be limited to cases where a third-party
135 library may need to control or free the memory, or when the memory in
136 question needs to survive between multiple requests.
137
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
138 Naming Conventions
139 ------------------
140
5cc6344 Updated to reflect recent discussions on php-dev.
Ron Chmara authored
141 [1] Function names for user-level functions should be enclosed with in
8e7147a - Use PHP_ instead of ZEND_
Derick Rethans authored
142 the PHP_FUNCTION() macro. They should be in lowercase, with words
aa20347 Updated naming standards as per 9/12 dev/doc discussion.
Ron Chmara authored
143 underscore delimited, with care taken to minimize the letter count.
5cc6344 Updated to reflect recent discussions on php-dev.
Ron Chmara authored
144 Abbreviations should not be used when they greatly decrease the
145 readability of the function name itself.
aa20347 Updated naming standards as per 9/12 dev/doc discussion.
Ron Chmara authored
146
147 Good:
148 'mcrypt_enc_self_test'
149 'mysql_list_fields'
150
151 Ok:
152 'mcrypt_module_get_algo_supported_key_sizes'
153 (could be 'mcrypt_mod_get_algo_sup_key_sizes'?)
154 'get_html_translation_table'
155 (could be 'html_get_trans_table'?)
156
157 Bad:
158 'hw_GetObjectByQueryCollObj'
159 'pg_setclientencoding'
5cc6344 Updated to reflect recent discussions on php-dev.
Ron Chmara authored
160 'jf_n_s_i'
161
162
163 [2] If they are part of a "parent set" of functions, that parent should
164 be included in the user function name, and should be clearly related
165 to the parent program or function family. This should be in the form
166 of parent_*.
167
168 A family of 'foo' functions, for example:
169 Good:
170 'foo_select_bar'
171 'foo_insert_baz'
172 'foo_delete_baz'
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
173
5cc6344 Updated to reflect recent discussions on php-dev.
Ron Chmara authored
174 Bad:
175 'fooselect_bar'
176 'fooinsertbaz'
177 'delete_foo_baz'
178
179 [3] Function names used by user functions should be prefixed
585e338 php4ize a bit.
Sterling Hughes authored
180 with "_php_", and followed by a word or an underscore-delimited list of
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
181 words, in lowercase letters, that describes the function. If applicable,
182 they should be declared 'static'.
183
5cc6344 Updated to reflect recent discussions on php-dev.
Ron Chmara authored
184 [4] Variable names must be meaningful. One letter variable names must be
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
185 avoided, except for places where the variable has no real meaning or
186 a trivial meaning (e.g. for (i=0; i<100; i++) ...).
187
8a5402c Fixed some spelling errors.
Egon Schmid authored
188 [5] Variable names should be in lowercase. Use underscores to separate
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
189 between words.
190
191
192 Syntax and indentation
193 ----------------------
194
195 [1] Never use C++ style comments (i.e. // comment). Always use C-style
196 comments instead. PHP is written in C, and is aimed at compiling
197 under any ANSI-C compliant compiler. Even though many compilers
198 accept C++-style comments in C code, you have to ensure that your
199 code would compile with other compilers as well.
200 The only exception to this rule is code that is Win32-specific,
201 because the Win32 port is MS-Visual C++ specific, and this compiler
202 is known to accept C++-style comments in C code.
203
204 [2] Use K&R-style. Of course, we can't and don't want to
45807e6 Jon Parise Added a brief section documenting the preference of tabs over spaces.
jparise authored
205 force anybody to use a style he or she is not used to, but,
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
206 at the very least, when you write code that goes into the core
207 of PHP or one of its standard modules, please maintain the K&R
208 style. This applies to just about everything, starting with
8a5402c Fixed some spelling errors.
Egon Schmid authored
209 indentation and comment styles and up to function declaration
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
210 syntax.
7d220af small clarification
Hartmut Holzgraefe authored
211
212 (see also http://www.tuxedo.org/~esr/jargon/html/entry/indent-style.html)
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
213
45807e6 Jon Parise Added a brief section documenting the preference of tabs over spaces.
jparise authored
214 [3] Be generous with whitespace and braces. Always prefer:
215
612d5b9 - spaces instead of tabs
Derick Rethans authored
216 if (foo) {
217 bar;
218 }
45807e6 Jon Parise Added a brief section documenting the preference of tabs over spaces.
jparise authored
219
612d5b9 - spaces instead of tabs
Derick Rethans authored
220 to:
45807e6 Jon Parise Added a brief section documenting the preference of tabs over spaces.
jparise authored
221
612d5b9 - spaces instead of tabs
Derick Rethans authored
222 if(foo)bar;
45807e6 Jon Parise Added a brief section documenting the preference of tabs over spaces.
jparise authored
223
8a5402c Fixed some spelling errors.
Egon Schmid authored
224 Keep one empty line between the variable declaration section and
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
225 the statements in a block, as well as between logical statement
226 groups in a block. Maintain at least one empty line between
227 two functions, preferably two.
228
45807e6 Jon Parise Added a brief section documenting the preference of tabs over spaces.
jparise authored
229 [4] When indenting, use the tab character. A tab is expected to represent
230 four spaces. It is important to maintain consistency in indenture so
231 that definitions, comments, and control structures line up correctly.
232
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
233 Documentation and Folding Hooks
234 -------------------------------
235
236 In order to make sure that the online documentation stays in line with
237 the code, each user-level function should have its user-level function
238 prototype before it along with a brief one-line description of what the
239 function does. It would look like this:
240
241 /* {{{ proto int abs(int number)
8a5402c Fixed some spelling errors.
Egon Schmid authored
242 Returns the absolute value of the number */
8e7147a - Use PHP_ instead of ZEND_
Derick Rethans authored
243 PHP_FUNCTION(abs)
585e338 php4ize a bit.
Sterling Hughes authored
244 {
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
245 ...
246 }
247 /* }}} */
248
249 The {{{ symbols are the default folding symbols for the folding mode in
25c3a3a Rasmus Lerdorf vim-6 does folding - clean up a bunch of missing folding tags plus
rlerdorf authored
250 Emacs and vim (set fdm=marker). Folding is very useful when dealing with
251 large files because you can scroll through the file quickly and just unfold
252 the function you wish to work on. The }}} at the end of each function marks
253 the end of the fold, and should be on a separate line.
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
254
255 The "proto" keyword there is just a helper for the doc/genfuncsummary script
256 which generates a full function summary. Having this keyword in front of the
257 function prototypes allows us to put folds elsewhere in the code without
258 messing up the function summary.
259
260 Optional arguments are written like this:
261
262 /* {{{ proto object imap_header(int stream_id, int msg_no [, int from_length [, int subject_length [, string default_host]]])
8a5402c Fixed some spelling errors.
Egon Schmid authored
263 Returns a header object with the defined parameters */
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
264
5cc6344 Updated to reflect recent discussions on php-dev.
Ron Chmara authored
265 And yes, please keep the prototype on a single line, even if that line
266 is massive.
267
268 New and Experimental Functions
269 -----------------------------------
270 To reduce the problems normally associated with the first public
271 implementation of a new set of functions, it has been suggested
272 that the first implementation include a file labeled 'EXPERIMENTAL'
273 in the function directory, and that the functions follow the
274 standard prefixing conventions during their initial implementation.
275
276 The file labelled 'EXPERIMENTAL' should include the following
277 information:
8a5402c Fixed some spelling errors.
Egon Schmid authored
278 Any authoring information (known bugs, future directions of the module).
5cc6344 Updated to reflect recent discussions on php-dev.
Ron Chmara authored
279 Ongoing status notes which may not be appropriate for CVS comments.
aceaabc Zeev Suraski PHP 4.0
zsuraski authored
280
d47e483 As per andi, similar names are for legacy reasons only.
Ron Chmara authored
281 Aliases & Legacy Documentation
282 -----------------------------------
283 You may also have some deprecated aliases with close to duplicate
aa20347 Updated naming standards as per 9/12 dev/doc discussion.
Ron Chmara authored
284 names, for example, somedb_select_result and somedb_selectresult. For
8a5402c Fixed some spelling errors.
Egon Schmid authored
285 documentation purposes, these will only be documented by the most
d47e483 As per andi, similar names are for legacy reasons only.
Ron Chmara authored
286 current name, with the aliases listed in the documentation for
aa20347 Updated naming standards as per 9/12 dev/doc discussion.
Ron Chmara authored
287 the parent function. For ease of reference, user-functions with
288 completely different names, that alias to the same function (such as
289 highlight_file and show_source), will be separately documented. The
290 proto should still be included, describing which function is aliased.
291
d47e483 As per andi, similar names are for legacy reasons only.
Ron Chmara authored
292 Backwards compatible functions and names should be maintained as long
293 as the code can be reasonably be kept as part of the codebase. See
8a5402c Fixed some spelling errors.
Egon Schmid authored
294 /phpdoc/README for more information on documentation.
Something went wrong with that request. Please try again.