PHP Functions
- A function is a code or statement block in a program.
- Perform some specific tasks.
- Used repeatedly in a program.
- Not execute automatically when a page loads.
- Executed by a call to the function.
- The name must start with a letter or an underscore, and NOT case-sensitive.
- Take information’s as a parameter, executes a block of statements, or perform operations on these parameters and return the result.
Uses of functions
- Reusability: Use a function at more than one time and in various places according to our requirement without any re-describe. It reduces the time and repetition of a single code.
- Easier error detection: We can detect an error easily by function because our program is divided into sub-parts which is known as functions, not in all program.
- Easily maintained: if we want to change any value or data multiple times in a program, then we can change it in their related function, not in all programs.
Creating a Function
While creating a user-defined function we need the following things:
- Any name ending with an open and closed parenthesis is a function.
- The name always begins with the keyword function.
- To call a function need its name followed by the parenthesis
- name start with an alphabet or underscore not any number, not case-sensitive.
syntax:-
function function_name(){
executable code;
}
Example:-
<?php
function f1()
{
echo "hello php";
}
// Calling the function
f1();
?>
Function Parameters or Arguments
- Parameters:- The information or variable, within the function’s parenthesis.
- Hold the values during runtime.
- Use many parameters with a comma (,) operator.
- Parameters accept inputs during runtime.
- Passing the values during a function call called arguments.
- Information passed to functions through arguments. An argument is a value passed to a function as a variable and a parameter is used to hold those arguments.
- Arguments are specified after the function name, inside the parentheses.
function function_name($first_parameter, $second_parameter) {
executable code;
}
Example:
<?php
// function along with three parameters
function add($num1, $num2, $num3)
{
$product = $num1 + $num2 + $num3;
echo "The product is $product";
}
// Caling the function
// Passing three arguments
add(2, 3, 5);
?>
PHP provides us with two major types of functions:
Built-in functions :
- Provides a huge collection of built-in library functions.
- Already coded and stored in form of functions.
- To use just call them as per requirement like, var_dump, fopen (), print_r(), gettype() and so on.
User-Defined Functions :
- Create our own customized functions.
- Can create our own packages of code and use them when they need them by calling it.
PHP is a Loosely Typed Language
- Automatically associates a data type to the variable, depending on its value.
- Not set in a strict sense, like adding a string to an integer without causing an error.
- In PHP 7, type declarations were added.
- Gives an option to specify the expected data type when declaring a function, and by adding The strict declaration, it will throw a "Fatal Error" if the data type mismatches.
- The
strict
declaration forces things to be used in an intended way.
Ex.
<?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
?>
Output :- 10
To specify strict
to set declare (strict_types=1)
on the very first line of the PHP file.
Ex:
<?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
?>
Output:-
PHP Fatal error: Uncaught TypeError: Argument 2 passed to addNumbers() must be of the type integer, the string is given.
Variable functions (Dynamic Function Calls)
- Function names as strings to variables and treat as variables exactly as the function name itself.
- This means PHP searches for a function and finds a variable which name just like the function name. So evaluates it on the variable, and will try to execute it.
- It can be used for call-backs, function tables, etc. Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require, and the like.
- Utilize wrapper functions to make use of any of these make as variable functions.
Ex.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello() {
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
Output : -
Hello
Variable functions are used in the following manner:-
Example #1 Variable function example
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
Object methods can also be called with the variable functions syntax.
Example #2 Variable method example
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
When calling static methods, the function call is stronger than the static property operator:
Example #3 Variable method example with static properties
<?php
class Foo
{
static $variable = 'static property';
static function Variable()
{
echo 'Method Variable called';
}
}
echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope.
?>
Example #4 Complex callable
<?php
class Foo
{
static function bar()
{
echo "bar\n";
}
function baz()
{
echo "baz\n";
}
}
$func = array("Foo", "bar");
$func(); // prints "bar"
$func = array(new Foo, "baz");
$func(); // prints "baz"
$func = "Foo::bar";
$func(); // prints "bar"
?>
Setting Default Values for a Function parameter
- PHP allows us to set default argument values for function parameters.
- If we do not pass any argument for a parameter with a default value then PHP will use the default set value for this parameter in the function call.
function function_name($first_parameter, $second_parameter=value) {
executable code;
}
Example:
<?php
// function with default parameter
function def ($str, $num=18)
{
echo "$str is $num years old \n";
}
// Caling the function
def ("Ram", 20);
// In this call, the default value 18
// will be considered
def ("Adam");
?>
Returning Values from Functions
- Return values to the part of the program from where it is called.
- The return keyword is used to return value back to the part of the program, from where it was called.
- The returning value may be of any type including the arrays and objects.
- The return statement also marks the end of the function and stops the execution after that and returns the value.
Example:
<?php
// function along with three parameters
function mul($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
return $product; //returning the product
}
// storing the returned value
$retValue = mul(2, 3, 5);
echo "The product is $retValue";
?>
Parameter passing to Functions
Two ways
Pass by Value:
- Passing arguments by value.
- The value of the argument gets changed within a function, not in the original value outside the function.
- A duplicate of the original value is passed as an argument.
Pass by Reference:
On passing arguments by reference (address of the value) where it is stored using ampersand sign(&).
the original value gets altered.
<?php // pass by value function val ($num) { $num += 2; return $num; } // pass by reference function ref (&$num) { $num += 10; return $num; } $n = 10; val ($n); echo "The original value is still $n \n"; ref ($n); echo "The original value changes to $n"; ?> |
Output:
The original value is still 10
The original value changes to 20
The Variable Scope
- The location of the declaration determines the extent of a variable's visibility within the PHP program.
- where the variable can be used or accessed.
- known as variable scope.
- By default, variables declared within a function are local and they cannot be viewed or manipulated from outside of that function,.
<?php // Defining function
function test()
{
$greet = "Hello World!"; echo $greet;
}
test(); // Outputs: Hello World!
echo $greet; // Generate undefined variable error
?>
Output:-
$greet inside function is: Hello World!
$greet outside of function is:
Ex.
<?php
$greet = "Hello World!";
// Defining function
function test(){
echo '<p>$greet inside function is: ' . $greet . '</p>';
}
// Generate undefined variable error
test();
echo '<p>$greet outside of function is: ' . $greet . '</p>';
?>
Output:-
$greet inside function is:
$greet outside of function is: Hello World!
The global Keyword
- It visible or accessible both inside and outside the function.
- Use the
global
keyword before the variables inside a function.
<?php
$greet = "Hello World!"; // Defining function
function test()
{
global $greet;
echo $greet;
}
test(); // Outpus: Hello World!
echo $greet; // Outpus: Hello World! // Assign a new value to variable $greet = "Goodbye";
test(); // Outputs: Goodbye
echo $greet; // Outputs: Goodbye
?>
Output:-
$greet inside function is: Hello World!
$greet outside of function is: Hello World!
$greet inside function is: Goodbye
$greet outside of function is: Goodbye
Recursive Functions
- A recursive function is a function that calls itself again and again until a condition is satisfied.
- Used to solve complex mathematical calculations, or to process deeply nested structures e.g., printing all the elements of a deeply nested array.
<?php
// Defining recursive function
function printValues($arr) {
global $count;
global $items;
// Check input is an array
if(!is_array($arr)){
die("ERROR: Input is not an array");
}
/* Loop through array, if value is itself an array recursively call the function, else add the value found to the output items array, and increment counter by 1 for each value found */
foreach($arr as $a){
if(is_array($a)){
printValues($a);
} else{
$items[] = $a;
$count++;
}
}
// Return total count and values found in array
return array('total' => $count, 'values' => $items);
}
// Define nested array
$species = array(
"birds" => array(
"Eagle",
"Parrot",
"Swan"
),
"mammals" => array(
"Human",
"cat" => array(
"Lion",
"Tiger",
"Jaguar"
),
"Elephant",
"Monkey"
),
"reptiles" => array(
"snake" => array(
"Cobra" => array(
"King Cobra",
"Egyptian cobra"
),
"Viper",
"Anaconda"
),
"Crocodile",
"Dinosaur" => array(
"T-rex",
"Alamosaurus"
)
)
);
// Count and print values in the nested array
$result = printValues($species);
echo $result['total'] . ' value(s) found: ';
echo implode(', ', $result['values']);
?>
Output:-
16 value(s) found: Eagle, Parrot, Swan, Human, Lion, Tiger, Jaguar, Elephant, Monkey, King Cobra, Egyptian cobra, Viper, Anaconda, Crocodile, T-rex, Alamosaurus.
<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
Recursion (5);
?>
Output:- 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
PHP static variables
- A static variable is a variable which lifetime extends across the entire run of the program.
- Use static keyword before the variable name.
- The default local variables do not hold their value within repeated calls of the function.
without static example:-
<?php
function nonstatic() {
$value = 0;
$value += 1;
return $value;
}
nonstatic();
nonstatic();
nonstatic();
nonstatic();
echo nonstatic(), "\n";
?>
Output:-
1
The static variables are initiated only once when the function is first called. They retain their value afterward.
static function example:-
<?php
function staticfun() {
static $value = 0;
$value += 1;
return $value;
}
staticfun();
staticfun();
staticfun();
staticfun();
echo staticfun(), "\n";
?>
Output:-
5987
0 Comments