Define and Call a Functions In PHP With Examples

In this topic of the PHP tutorial, we talk about

Define and Call a functions in PHP with example

A function is playing a key role in programming language. It has more than 1000 built-in functions. The function performs a specific task. The upsides of utilizing capacities are:

  • Reducing duplication of code
  • Decomposing complex problems into simpler pieces
  • Improving clarity of the code
  • Reuse of code
  • Information hiding

There are two types of functions in php with example:

  1. Built-in functions – The built-in functions are part of the PHP language. Examples are: phpinfo(), round() or abs().
  2. User defined – The user defined functions are created by application programmers to cover their needs. They are created with the function
    1. A function will not execute immediately when a page loads.
    2. A function will be executed by a call to the function.
    3. Function names are NOT case-sensitive.

Create a User Defined Function in PHP

Define and Call A function is created with the ‘function’ keyword.

Note: A function name can start with a letter or underscore (not a number).

The function keyword is followed by the function name with round brackets. The body of the function lies between the curly brackets. We say that we call a function. If we call a function, the statements inside the function body are executed.

PHP Function Arguments:- Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

Function with arguments ($Script):

Function with two arguments ($name and $yr):

PHP Default Argument Value

How to use a default parameter. If we call the function DTH() without arguments it takes the default value as argument:

The return keyword

The return keyword is used to return a value from the function. A function may or may not return a value.

Trust this instructional exercise helped you a lot, keep reading our various posts for more coding Tricks and Tips. If you like this article do me favor by sharing it with your friends.

Digital Technology Hub