Functions In PHP

Our goal here is to take a deeper dive into PHP functions with examples, exploring what they are, how they are defined, and how they are called.

PHP functions are blocks of code that can be repeated within your code.

A function performs a specific task and takes parameters and returns values.

Functions help you organize your code, make it easier to read and maintain, and reduce the amount of code you have to write.

There are more than 1000 pre-built functions in PHP, and you can also write your own custom functions.



Built-in PHP Functions

There are more than 1000 built-in PHP functions that can be accessed directly within a script in order to perform a specific task.

PHP built-in functions are predefined functions.

A built-in function performs basic tasks, such as modifying strings, working with arrays, and performing mathematical calculations.

Using these functions in your code will make your code more efficient, readable, and maintainable.

Built-in functions are easy to use. All you need to do is call the function by name and pass in any parameters.


User Defined Functions In PHP

Besides built-in PHP functions, developers can also define their own functions. These functions are called user-defined functions, which are used to limit a block of code to perform a specific task using a set of variables.

A function is a set of instructions that form the structure of a program and can be used repeatedly throughout the program.

When a page loads, a function will not automatically execute when it is loaded.

By calling the function, the function is executed.

Following are a few simple steps you can take in order to create a user-defined function in PHP:

1 – The first thing you need to do is use the function keyword, followed by the name you want to give the function. Use a descriptive name that reflects the function’s purpose.

2 – After that, we need to include any parameters that the function will accept between parentheses in the function declaration.

Parameters are variables that are passed to the function when it is called. These can be used to provide input to functions.

3 – In the function block, you should write the code that you want to run when the function is invoked, so that the code can be executed. You can enter any valid PHP code here, including other function calls, loops, conditionals, as well as any other valid PHP code.

4 – To finish, specify the return value the function should return. As for the value, it can be of any data type, whether it be a string, an integer, an array, etc.

Syntax

function functionName()
{
//The code that needs to be executed.
}
Remember: Function names should begin with a letter or an underscore. There is no case sensitiveness when it comes to the names of functions.

The example below shows an example of how to create a function named “greeting()“. There is a curly brace ( { ) at the beginning of the code that indicates the beginning of the function, and a curly brace ( } ) at the end that indicates the end of the function code.

This function will output the message “Good morning”. In order to invoke a function, write the function name using brackets ():

Example: 

<?php function greeting() { echo "Good Morning!"; } greeting(); // invoking the function ?>
Hint: Make sure your function is named in a way that makes it clear what it is supposed to do.

Below is another example of greeting with a name by creating a function:

Example: 

<?php function userGreeting() { $name = "Ben"; echo "Good Morning!, " . $name ; } userGreeting(); // invoking the function ?>

Php Functions


PHP Function Arguments

PHP Functions can be passed information through arguments. Arguments are just like variables. After the function name, the arguments are enclosed in parentheses.
In PHP functions, you are allowed to have as many arguments as you like, separated by commas.
In the following example, there is one argument ($firstname) to the function. The function familyMembers() takes as input a name (for example, “Brock”). Within the function, the name is used to output several different first names, but an equal last name, which we then use in the output:

Example: 

<?php function familyMembers($firstname) { echo "$firstname Lesnar. <br>"; } familyMembers("Brock"); familyMembers("Rena Marlette"); familyMembers("Mya Lynn"); familyMembers("Duke"); familyMembers("Luke"); ?>
Below is another example of creating a function using a parameter:

Example: 

<?php function pets($name) { echo "$name <br>"; } pets("Dogs"); pets("Cat"); pets("Rabbit"); ?>
Here is an example below where a function has two parameters ($firstname and $date_of_birth):

Example: 

<?php function familyMembers($firstname, $date_of_birth) { echo "$firstname is born on $date_of_birth <br>"; } familyMembers("Brock", "1977"); familyMembers("Rena Marlette", "1967"); familyMembers("Turk", "2009"); ?>
Here is another example of creating function pets() with two parameters: First as a $name, and second as a $dayStay:

Example: 

<?php function pets($name, $dayStay) { echo "$name alive till $dayStay years.<br>"; } pets("Dogs", "11"); pets("Cat", "10 to 15"); pets("Rabbit", "9"); ?>

Loosely typed PHP

Notice, in the example above, that we didn’t have to tell PHP what data type the variable was.
Variables are automatically associated with data types based on their values.
As data types are not set in a very strict sense, you are free to add a string to an integer without it causing you any trouble.
PHP 7 introduced type declarations. A strict declaration allows us to specify the expected data type when declaring a function, and if the type is mismatched, a “Fatal Error” will occur.
As an example, let’s send a number and a string without using strict:

Example: 

<?php function sum(int $x, int $y) { return $x + $y; } echo sum(10, "4"); // since strict is NOT enabled "4" is changed to int(4), and it will return 14 ?>
Now, let’s create one more function to calculate the square root without using strict:

Example: 

<?php function sqRoot(int $x) { return $x *$x; } echo sqRoot("3"); // since strict is NOT enabled "3" is changed to int(3), and it will return 9 ?>

The declaration of strict types can be accomplished by declaring (strict_types=1);.

PHP files must have this on the first line.

Now, using the strict declaration we send both a number and a string to the sum() function in the below example:

Example: 

<?php declare(strict_types = 1); // strict requirement function sum(int $x, int $y){ return $x + $y; } echo sum(10, "4"); // since strict is enabled and "4" is not an integer, an error will be thrown ?>
Important: In PHP 8, strict_types is deprecated.

Following is another example of creating sqRoot() function using strict declaration:

Example: 

<?php declare(strict_types = 1); // strict requirement function sqRoot(int $x) { return $x *$x; } echo sqRoot("3"); // since strict is enabled and "3" is not an integer, an error will be thrown ?>
Remember: In PHP 8, strict_types is deprecated.

Strict declarations force things to be used as intended.


PHP Default Argument Value

Default argument values are assigned to function parameters when they are not explicitly passed in.

It allows functions to be called with fewer arguments than they require and provides a default value if arguments are missing.

In the following example, we will see how to use a default parameter.

The default value is taken as an argument if we call the function setAge() without any arguments:

Example: 

<?php declare(strict_types=1); // strict requirement function setAge(int $minAge = 12) { echo "The age is : $minAge"; } setAge(16); setAge(); // will use the default value of 50 setAge(20); setAge(35); ?>
Note: strict_types is deprecated in PHP 8 and above.

Here is an example, where we create a function called setGender() with the default value of $gender = “O” (other):

Example: 

<?php function setGender(int $gender = "O") { echo "The gender is : $gender "; } setGender("M"); setGender(); // will use the default value of O setGender("F"); setGender( "M"); ?>

In another example, we are about to return the square root value:

Example: 

<?php function sqRoot(int $a) { $b = $a * $a; return $b; } echo "Square root of 4 = " . sqRoot(4) . ""; echo "Square root of 25 = " . sqRoot(25) . ""; echo "Square root of 64 = " . sqRoot(64); ?>

Return Type Declarations In PHP

The return statement in PHP 7 also supports Type Declarations.

If you want to declare a return type for a function, you will need to add a colon ( : ) and the type before the opening curly ( { ) bracket when declaring the function.

As an example, let’s specify the return type for a function in the following way:

Example: 

<?php function sum(float $x, float $y) : float { return $x + $y; } echo sum(3.4, 6.6); ?>
Returning an int value from the sqRoot() function, in the example below:

Example: 

<?php declare(strict_types=1); // strict requirement function sqRoot(int $x) : int{ return $x * $x; } echo sqRoot(3); ?>

Return types can be different from argument types, but make sure they are the right type as we return the float values into int in the example below:

Example: 

<?php declare(strict_types=1); // strict requirement function sum(float $x, float $y) : int{ (int) return $x + $y; } echo sum(3.4, 6.6); ?>
Important: In PHP 8, strict_types = 1 and return type declarations are deprecated.
Here, we specify the float return type to the int values:

Example: 

<?php declare(strict_types=1); // strict requirement function sqRoot(int $x) : float{ return (float) $x * $x; } echo sqRoot(3); ?>
Important: In PHP 8, strict_types = 1 and return type declarations are deprecated.

Passing Arguments by Reference

A PHP function uses arguments by value. This means that a copy of the argument is used in the function. In addition, the variable that has been passed into the function can’t be changed if the value has been passed by value.

By passing a function argument by reference, changes to the argument will also cause a change to the variable that was passed into the function.

In order to convert PHP function argument into a reference, we need to use the & operator.

In the example below, we update the value by using the pass-by-reference argument:

Example: 

<?php function addTwo(&$a) { $a += 2; } $value = 7; addTwo($value); echo $value; ?>
Here, we are updating the value of a string using pass-by-reference:

Example: 

<?php function strPrinting( &$str ) { $str = "String Inside the function <br>"; print( $str ); } $str = "String outside the function <br>"; strPrinting( $str ); print( $str ); ?>

Example Explanation

In above example we have defined a function called strPrinting and then calls it with the argument $str.

The strPrinting function takes a single parameter &$str, which is a reference to a variable outside the function.

The & symbol before $str indicates that it’s a reference parameter. This means that any changes made to this parameter inside the function will also affect the variable outside the function.

Inside the function, the value of $str is changed to “String Inside the function <br>” and then printed to the screen using the print function.

Then, function is called with an argument $str, which is initialized to “String outside the function <br>”. This means that the value of $str inside the function will also be “String outside the function <br>”, but will be changed to “String inside the function <br>” when the strPrinting function is called.

Finally, after the function call, the value of $str is printed again, which will be “String Inside the function <br>” since it was changed inside the function.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *