2Reusing Code. Functions. Topics:Code inclusion using require() and include()Defining functionsManaging function parametersPassing-by-reference vs. passing-by-valueParameters default valuesVariable-length parameter listsUnderstanding variable scope in functionsUsing functions to return valuesUsing recursive functionsAnonymous functions
4Modularity - why? … has a favorable impact on program development: Allows program to be divided into logical pieces:Level of difficulty grows with the size and complexity of a programDivide work among programmersEasier to debug when modules are tested alone fully first, then integrated systematicallyEasier to read, especially when commented correctly.Easier to modify, isolating modules to changeAllows for reuse (avoiding redundant code); when an algorithm or computation is done over and over, it can be put in a method.
5Code InclusionPHP allows to reuse any type of code (not only functions, classes):Can insert code from a file into your PHP script with include (‘filename’); require (‘filename’);Statements include() & require() are similar, except when they fail:include() construct just gives a warning if failing to include filerequire() construct gives a fatal error, that will cause program to terminateCan also use variations include_once() or require_once() to avoid problems with redundancy; ex. redefining same functionSlower than include()/require()
7Code InclusionThe files loaded using include / require can contain everything that is normally used in a PHP file: PHP statements, PHP functions, PHP classes, HTML code, client-side scriptingPHP code still has to be placed within PHP tagsFilename extensions:When include()/require() is used in a PHP script: the loaded file becomes part of the PHP script and is executed as such → as if the loaded file’s contents replaced the include()/require() statementPHP does not look at the filename extension of an included file include files can have any extension, if not to be used directly.Usually: .php or .inc (note: if located in the web document tree, their content can be seen in clear!)
10Code InclusionThe include files can be dynamic and generate on-the-fly parts of the pageApache or PHP can be configured to automatically load specific pages / files before and after every page, even for individual directories (applications) include() statements not needed in this caseNot on cscdb…