Top 15 PHP Function Secrets Developers Must Know
PHP has a server-side programming language provides a plentiful number of functions to play with. These internal functions are useful in many ways and act as an effective utility tool while development and also developers can define custom functions which will even enhance its effectiveness.
So in this tutorial, You’ll be learning Top 15 PHP Function Secrets Developers Must Know.
Define Function in PHP
For those who are new to PHP programming, this is how functions are defined. You need to use the keyword function
and followed by the function name. Parameters to functions are passed inside brackets and to call function simple use its name and followed by brackets.
<?php // Defining Function here function function_name(arguments){ // statements } function_name(); //calling function here
Example:
<?php function show_name(){ echo "My name is: Sumit"; } show_name(); // My name is: Sumit
PHP Function Naming Convention
There are certain common programming standards which must be followed every programming language and these same rules of naming functions are also applied to PHP language and they are listed below.
- No Special Characters must be used however underscore _ are an exception.
- Self Explanatory Function Name: The user must get an idea of what the purpose of the function is just by reading its name.
- Avoid Duplicate or Similar Names: Each function name must be different from one another as it eliminates ambiguity.
- No Numerical Values: Functions should not contains and numerical values such as get1stUser[wrong], get_first_user[right and acceptable].
- Lower Case Names are recommended: You are free to use the function name as Full Upper case or Capitalized. But for readability purpose, it is recommended to use function names as lower case and underscore to separate the words for ease of readability.
1 – Functions with Argument
Our First secret starts with passing arguments to function. You can specify as many numbers of arguments you want to be followed by a comma.
function show_name($name, $age){ echo "My name is ".$name." and i'm ".$age." years old"; } show_name("Sumit", 21); //My name is: Sumit and i'm 21 years old
2 – Functions with Default Arguments
If you would like to keep a particular function argument as optional which calling it then you can give it a default value. While calling function if the argument is not passed that the default value of an argument is assigned to parameter just like $interest=1.5
. If interest value is not passed than PHP will consider argument $interest
value as 1.5.
function loan_information($amount, $interest=1.5){ echo "For amount ".$amount." interest = ".$interest."/yearly will be charged."; } loan_information(1000); //For amount 1000 interest = 1.5/yearly will be charged.
Argument Type Hinting
By default, PHP is a weak type and if you want to force PHP for strict type checking of function arguments than specify the datatype of argument within the brackets followed by parameter name.
function loan_information(float $amount, float $interest=1.5){ var_dump($amount); var_dump($interest); } loan_information("1", "1.25"); //OUTPUT /var/www/html/TestProject/examples/php/functions.php:12:float 1 /var/www/html/TestProject/examples/php/functions.php:13:float 1.25
Even if you have passed string arguments because of strict check PHP implicitly type casts numerical string into float. But when an alphabetical string is passed it throws a Notice: A non well formed numeric value encountered
.
3 – Pass Function as Argument
This is a very simple way as you can passing function name as an argument to the function and call that argument inside the function as regular function like $func();
.
function func_a($func){ $func(); } function func_b(){ echo "Function B is called"; } func_a('func_b'); // prints Function B is called
There is also another way where you can pass anonyms function directly into a function parameter.
function func_a($func){ $func(); } func_a(function(){ echo "Function B is called"; }); // prints Function B is called
However, this method is not so practical and to not possible to reuse it.

Udemy PHP Course
4 – Variadic function
Let’s assume a scenario where you have to pass N number of arguments to function and if you go in traditional way you have to give value to each and every argument. But using Variadic functions you can unpack the function arguments without even mentioning their names.
Use (…) inside function argument brackets has used in below example where …$extra_agrs is a splat operator.
function employee_information($name, ...$extra_agrs){ echo "Name: ".$name."<br>"; echo "Designation: ".$extra_agrs[0]."<br>"; echo "Age: ".$extra_agrs[1]."<br>"; } $name="Kushal"; $designation = "Software Developer"; $age="22"; employee_information($name, $designation, $age); // OUTPUT Name: Kushal Designation: Software Developer Age: 22
The argument $extra_agrs
is an array which contains arguments and to access the argument use index number.
There is also an alternate way by using the func_get_args()
a function which returns the function arguments in the form of an array.
Example:
The below function using func_get_args() function will display the same output as above.
function employee_information($name){ echo "Name: ".$name."<br>"; echo "Designation: ".func_get_args()[1]."<br>"; echo "Age: ".func_get_args()[2]."<br>"; }
What’s Inside the func_get_args()
If you debug func_get_args()
function using the var_dump()
then below is how the output looks.
function employee_information($name){ var_dump(func_get_args()); }
Note
We recommend it better not to use splat operator is side functions as in large projects you cannot track the sequence of arguments you will be passing. Because there are high chances that function may throw an exception or will evaluate the wrong value. But insisted of this you can pass option argument which takes an associative array as a parameter.
5 – Access Global Variables inside functions
In PHP Functions, Global variable scope works kind of differently compared to other programming languages were to need just declare a variable outside function and then you can freely access those variables within any function as the variable is global in scope.
But in PHP programming accessing these variables directly inside the function will throw Notice: Undefined variable: name
. This is because in PHP all the global variables are stored in a $GLOBALS array.
Quick Note
Turn on error error_reporting(E_ALL);
and ini_set('display_errors', "1");
and the top of PHP script to enable the display of errors.
Example
$name = "Sunil"; function show_name(){ echo $name; //As per PHP Functions, vairable $name is undefined. } show_name(); // OUTPUT Notice: Undefined variable: name in /var/www/html/TestProject/examples/php/functions.php on line 9
There are two ways to access global variables. The first is to use $GLOBALS
variable or the global
keyword.
Example:
$name = "Sunil"; $age = 29; function show(){ global $age; echo "My friend ".$GLOBALS['name']." is ".$age." years old."; } show(); // OUTPUT My friend Sunil is 29 years old.
The keyword global
will directly fetch the value from the $GLOBALS
the variable has the local variable $age
matches the name of the global variable. And if the global variable of a variable doesn’t exist then a NULL
value is directly assigned.
6 – Function Return Type Declaration
The Function Return Type Declaration support was added in PHP 7 version. Through this, you can specify which datatype the function must return. To use this declaration you must add declare(strict_types = 1);
at the first of your script else will not work as expected.
<?php declare(strict_types = 1); error_reporting(E_ALL); ini_set('display_errors', "1"); function add_cart_items(): int { return 1 + 3; } echo "The total number of items in cart are ".add_cart_items(); // OUTPUT The total number of items in cart are 4
Note
While using strict_types make sure you add declare(strict_types = 1); at the very first statement before adding any logic. If not than PHP Fatal error: strict_types declaration must be the very first statement in the script will be thrown.
If the function returns other datatype value apart from what it is declared than TypeError exception is thrown.
<?php declare(strict_types = 1); error_reporting(E_ALL); ini_set('display_errors', 1); function add_cart_items(): int { return 1 + 3 + 4.5; } echo "The total number of items in cart are: ".add_cart_items(); // OUTPUT PHP Fatal error: Uncaught TypeError: Return value of add_cart_items() must be of the type integer, float returned
Tip
You can also specify a Nullable return type declaration using the symbol (?).
declare(strict_types = 1); function return_null():?int{ return NULL; } return_null(); // Output is NULL
The symbol in between colon and return type (:?int) informs PHP interpreter to allow NULL type returns.
7 – Anonymous or Closure Functions
Functions with closures or no names defined are considered as anonymous functions. Look at below example to create one.
$add_number = function($a, $b){ return $a+$b; }; echo "The number is ".$add_number(1, 2); // OUTPUT The number is 3
Anonymous Function inside another Function
You can also declare anonymous functions inside other function and the procedure remains the same.
function cart_items(){ $items = [ "soap", "face wash", "biscuits" ]; $item_count = function() use ($items){ return count($items); }; echo "There total " .$item_count() . " number of items in the cart"; } echo cart_items(); // OUTPUT There total 3 number of items in the cart
Scoping inside an Anonymous closure function
To use outside variables inside closure pass those variables through use ($outside_variable_one, $outside_variable_two. …) else you will be displayed variable as undefined.
$items = [ "soap", "face wash", "biscuits" ]; $item_count = function(){ return count($items); }; // OUTPUT Notice: Undefined variable: items
Using Super Global variables inside an anonymous function
You can use superglobal variables such as $GLOBALS
, $_POST
, $_GET
etc within an anonymous function without the need to pass it through use function.
function foo(){ $bar = function(){ var_dump($GLOBALS); // This works }; $bar(); } foo();
8 – Check Function exists
Use internal function function_exists
to check whether the function exists within the current context.
function foo(){ /* statements */ } if( function_exists( 'foo' ) ){ echo "Yes the function foo() exits"; } else { echo "No the function foo() does not exits"; } // OUTPUT Yes the function foo() exits
if( function_exists( 'bar' ) ){ echo "Yes the function bar() exits"; } else { echo "No the function bar() does not exits"; } // OUTPUT No the function bar() does not exits
9 – Find were function is defined.
For any purpose, if you want to get the file name and the starting line of function declaration than using built-in ReflectionFunction
class. It takes function name as a parameter and returns an object which contains all the meta information of that function.
In File my_new_functions.php.
<?php function get_employee_details(){ echo "Inside get_employee_details() function"; }
In File functions.php.
<?php include "my_new_functions.php"; $ref_function = new ReflectionFunction('get_employee_details'); echo "The Function: <strong>" . $ref_function->getName() . "</strong> is defined in file <strong>" . $ref_function->getFileName() . "</strong> at line number <strong>" . $ref_function->getStartLine() . "</strong>"; // OUTPUT The Function: get_employee_details is defined in file /var/www/html/TestProject/examples/php/my_new_functions.php at line number 2
10 – Using Variables inside Function
Using static variables inside functions.
function counter(){ static $counter = 0; $counter+=1; echo $counter."<br>"; } echo counter(); echo counter(); echo counter(); // OUTPUT 1 2 3
Use the function define()
for defining any constants in PHP.
define('website_name', "thecodelearners.com"); function info(){ echo website_name."<br>"; } echo info(); echo info(); // OUTPUT thecodelearners.com thecodelearners.com
11 – Get the name of calling function
Use PHP’s debug tracking function debug_backtrace()
which will get you a traceback of the previous function called by sequence. You can take a look at below given snippet.
function rock(){ paper(); } function paper(){ scissor(); } function scissor(){ var_dump(debug_backtrace()); } rock();
12 – Display how many times the function is called
Use the static
keyword and increment the number in the variable $counter
to get the number of times the function was called.
function foo(){ static $counter = 0; $counter+=1; return $counter; } echo "This Function is called <strong>".foo()."</strong> number of times.<br>"; echo "This Function is called <strong>".foo()."</strong> number of times.<br>"; echo "This Function is called <strong>".foo()."</strong> number of times.<br>"; echo "This Function is called <strong>".foo()."</strong> number of times.<br>"; echo "This Function is called <strong>".foo()."</strong> number of times.<br>"; // OUTPUT This Function is called 1 number of times. This Function is called 2 number of times. This Function is called 3 number of times. This Function is called 4 number of times. This Function is called 5 number of times.
13 – Get the name of the current function
To retrieve the current function name use the magic constant __FUNCTION__
which returns the current file name.
function add_employee(){ echo "The current function name is <strong>". __FUNCTION__ ."</strong>.<br>"; } function promote_employee(){ echo "The current function name is <strong>". __FUNCTION__ ."</strong>.<br>"; } add_employee(); promote_employee(); // OUTPUT The current function name is add_employee. The current function name is promote_employee.
14 – Returning a reference from a function
Consider a case where you want to bind the function return value to an outside variable. As you update the outside variable the function return variable also gets updated has it is referenced.
function &fruits(){ static $items = ["Mango"]; return $items; } $cart = &fruits(); array_push($cart, "Apple"); array_push($cart, "Grapes"); echo "<h2>Cart Items</h2>"; var_dump($cart); echo "<br><br><h2>Items returned by Function fruits()</h2>"; var_dump(fruits());
15 – Convert function into a string
Through method __toString()
by using ReflectionFunction()
the class you can convert the function into a string.
function my_func($name, $age=26){ $salary = 15000; echo "Hello PHP"; } $ref_function = new ReflectionFunction('my_func'); $string_represented_function = $ref_function->__toString(); var_dump($string_represented_function);
Conclusion
In Conclusion, I hope you have learnt something new related to PHP functions of our post on Top 15 PHP Function Secrets Developers Must Know. Comment if you have more secrets and don’t forget to share this article.
Related Posts
- PHP sending email using mail() function
- Laravel Jobs and Queues – Configuring, Sending Mail, Dispatching Jobs




