Menu

  •    
  • Home
  • Digital Accessibility
  • Web Accessibility Testing
    • Testing Principles
    • Automated Testing
  • Accessible Learning Materials
  • Development Principles
  • Inclusion in the learning process
  • HTML
    • HTML Syntax
    • Text Tags
  • CSS
    • CSS Syntax
    • Text Formatting CSS
  • PHP
    • PHP Syntax
    • PHP Functions

Contacts

  • t.todorov@ts.uni-vt.bg
  • 5003 Veliko Tarnovo, Bulgaria, Teodosii Turnovski St. #2

PHP Functions

PHP user-defined functions

Besides the built-in PHP functions, it is possible to create your own functions:
  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not be executed automatically on page load.
  • A function will be executed by calling the function.
A user function declaration begins with the word function:

function functionName() {
 code to be executed;

}
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call a function, its name must be written followed by parentheses ():

Hello world!
Information can be passed to functions via arguments. An argument is just like a variable. Arguments are specified after the function name, in parentheses. You can add as many arguments as you want, just separate them with commas. The following example defines a function with one argument ($fname). When the familyName() function is called, a name is passed (e.g. Jani) and the name is used in the function, which outputs several different first names but the same last name:

&lt;?php function familyName($fname) { echo "$fname Refsnes.<br>"; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?>
The following example declares a function with two arguments ($fname and $year):

&lt;?php function familyName($fname, $year) { echo "$fname Refsnes. Born in $year <br>"; } familyName("Hege", "1975"); familyName("Stale", "1978"); familyName("Kai Jim", "1983"); ?>