THE WORLD'S LARGEST WEB DEVELOPER SITE

PHP7 Tutorial

PHP7 HOME PHP7 Intro PHP7 Install PHP7 Syntax PHP7 Variables PHP7 Echo / Print PHP7 Data Types PHP7 Strings PHP7 Constants PHP7 Operators PHP7 If...Else...Elseif PHP7 Switch PHP7 While Loops PHP7 For Loops PHP7 Functions PHP7 Arrays PHP7 Sorting Arrays PHP7 Superglobals

PHP7 Forms

PHP7 Form Handling PHP7 Form Validation PHP7 Form Required PHP7 Form URL/E-mail PHP7 Form Complete

PHP7 Advanced

PHP7 Arrays Multi PHP7 Date and Time PHP7 Include PHP7 File Handling PHP7 File Open/Read PHP7 File Create/Write PHP7 File Upload PHP7 Cookies PHP7 Sessions PHP7 Filters PHP7 Filters Advanced

MySQL Database

MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Delete Data MySQL Update Data MySQL Limit Data

PHP7 XML

PHP7 XML Parsers PHP7 SimpleXML Parser PHP7 SimpleXML - Get PHP7 XML Expat PHP7 XML DOM

PHP7 - AJAX

AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll

PHP7 Reference

PHP7 Overview PHP7 Array PHP7 Calendar PHP7 Date PHP7 Directory PHP7 Error PHP7 Filesystem PHP7 Filter PHP7 FTP PHP7 Libxml PHP7 Mail PHP7 Math PHP7 Misc PHP7 MySQLi PHP7 Network PHP7 SimpleXML PHP7 Stream PHP7 String PHP7 XML Parser PHP7 Zip PHP7 Timezones

PHP 7 Functions


The real power of PHP comes from its functions; it has more than 1000 built-in functions.


PHP User Defined Functions

Besides the built-in PHP functions, we can create our own functions.

A function is a block of statements that can be used repeatedly in a program.

A function will not execute immediately when a page loads.

A function will be executed by a call to the function.


Create a User Defined Function in PHP

A user-defined function declaration starts with the word function:

Syntax

function functionName() {
    code to be executed;
}

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

Tip: Give the function a name that reflects what the function does!

Function names are NOT case-sensitive.

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

Example

<?php
function writeMsg() {
    echo "Hello world!";
}

writeMsg(); // call the function
?>
Try it Yourself »


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.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

<?php
function familyName($fname) {
    echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Try it Yourself »

The following example has a function with two arguments ($fname and $year):

Example

<?php
function familyName($fname, $year) {
    echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
Try it Yourself »

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing and error.

In PHP 7, type declarations were added. This gives us an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.

In the following example we try to add a number and a string with without the strict requirement:

Example

<?php
function addNumbers(int $a, int $b) {
    return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?>
Try it Yourself »

In the following example we try to add a number and a string with with the strict requirement:

Example

<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {
    return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?>
Try it Yourself »

To specify strict we need to set declare(strict_types=1);. This must be the on the very first line of the PHP file. Declaring strict specifies that function calls made in that file must strictly adhere to the specified data types

The strict declaration can make code easier to read, and it forces things to be used in the intended way.

Going forward in this tutorial, we will use the strict requirement.


PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example

<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
    echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Try it Yourself »

PHP Functions - Returning values

To let a function return a value, use the return statement:

Example

<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
    $z = $x + $y;
    return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Try it Yourself »

PHP Return Type Declarations

PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( { )bracket when declaring the function.

In the following example we specify the return type for the function:

Example

<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
    return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
Try it Yourself »

You can specify a different return type, than the argument types, but make sure the return is the correct type:

Example

<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
    return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
Try it Yourself »