Php how to create functions

PHP — Functions in PHP — How to create and how to use

In programming aspects, A Functions is a chunk of Code which can be executed multiple times without writing it again and again.
Or, A Functions is a chunk of code which can do specific type of task.

¶Functions in PHP

In PHP there are almost 1000+ built in functions. We’ve already used some of the built in functions in our previous chapter about — Math, String and Array Built in Functions.

Today, we’ll learn Custom user defined function in PHP.

¶How to Create & Use Custom User defined Function in PHP

Let’s create a simple custom user defined function in PHP —

 // Use this function funtionName(); 
  1. To start any function in PHP, we start with function keyword.
  2. After then adding a space and give function name, here — functionName would be your custom function name, eg: printHello() , calculateAge(«2000-01-01») etc.
  3. Function name must be start with letter or underscore
  4. Function name is not case-sensitive.
  5. Inside the first parenthesis () , we can pass any number variable, where we’ld call it. We would call that Argument. So, we can pass any number of argument.
  6. After the argument, there would be second curly braces start and stop <> .
  7. Inside the second curly braces <> we can write our specific tasks code.

Let’s Check some Real-life Function Example —

¶Example 1: Make a function that Print Hello World —

function printHelloWorld() < echo "Hello World"; >// Use this printHelloWorld(); // Hello World 

¶Example 2: Make a function that can tell if Age is Child, Adult or Old

function getAge($age) < if ($age >= 0 && $ageage < 18) < echo "You are aaaa Child"; >elseif ($age >= 18 && $age < 50) < echo "You are an AdAdultult"; >elseif ($age >= 50) < echo "You are Old"; >> // Use this getAge(25); // You are an Adult getAge(16); // You are a Child getAge(70); // You are Old 

¶Argument in Function

In our above Second example, we’ve passed an age integer value while we use this function.

This passed $age variable is the Argument. We can use as many argument as our necessity in functions.

But, practically it’s not good to use more than 4-5 arguments, cause thus makes the code more unreadable. Maximum 2-3 arguments for a function is standard.

¶Function Argument Pass by Value

 $count = 5; getPassByValue($count); echo "Pass by value::" . $count . "
"; // 5

Normally, if we pass any variable as argument to a function, then we actually pass the value of the variable. And whatever, we do inside that function, does not effect the passed variable.
This is the Passed by value example. Normally we use this kind of stuffs most of the time.

¶Function Pass by Reference

 $count = 5; getPassByReference($count); echo "Pass by reference::" . $count; // 10 

Now to pass the reference of the variable, we can do that by adding & before function’s argument name. Like the above example —

function getPassByReference(&$value) 

And from calling part, we create a variable $count = 5 , but after calling that function — getPassByReference($count); After that the $count variable changed to 10, that’s because, we passed the reference of that variable. And after updating that reference inside the function, we actually updated the $count variable.
This is the Pass by reference.

Читайте также:  Профессиональный typescript бориса черного

¶Recursive Function

There is a special type of function which is called directly or indirectly by the own function is Recursive function.

¶Example of a Recursive Function

  > // Call that function once printNumberUpto20(1); ?> 

So, in Recursive function there would be some criteria —

  1. Own function will be called. For the above example, look printNumberUpto20($a + 1); the function was called itself.
  2. Function must need to break in a condition. For the above example — $a

Источник

create_function

This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

Description

Creates a function dynamically from the parameters passed, and returns a unique name for it.

This function internally performs an eval() and as such has the same security issues as eval() . It also has bad performance and memory usage characteristics, because the created functions are global and can not be freed.

A native anonymous function should be used instead.

Parameters

It is normally advisable to pass these parameters as single quoted strings. If using double quoted strings, variable names in the code need to be escaped carefully, e.g. \$somevar . args

The function arguments, as a single comma-separated string.

Return Values

Returns a unique function name as a string, or false on failure. Note that the name contains a non-printable character ( «\0» ), so care should be taken when printing the name or incorporating it in any other string.

Examples

Example #1 Creating a function dynamically, with create_function() or anonymous functions

You can use a dynamically created function, to (for example) create a function from information gathered at run time. First, using create_function() :

$newfunc = create_function ( ‘$a,$b’ , ‘return «ln($a) + ln($b) color: #007700″>);
echo $newfunc ( 2 , M_E ) . «\n» ;
?>

Now the same code, using an anonymous function; note that the code and arguments are no longer contained in strings:

The above example will output:

ln(2) + ln(2.718281828459) = 1.6931471805599

Example #2 Making a general processing function, with create_function() or anonymous functions

Another use could be to have general handler function that can apply a set of operations to a list of parameters:

function process ( $var1 , $var2 , $farr )
foreach ( $farr as $f ) echo $f ( $var1 , $var2 ) . «\n» ;
>
>

// create a bunch of math functions
$farr = array(
create_function ( ‘$x,$y’ , ‘return «some trig: «.(sin($x) + $x*cos($y));’ ),
create_function ( ‘$x,$y’ , ‘return «a hypotenuse: «.sqrt($x*$x + $y*$y);’ ),
create_function ( ‘$a,$b’ , ‘if ($a >=0) ),
create_function ( ‘$a,$b’ , «return \»min(b^2+a, a^2,b) = \».min(\$a*\$a+\$b,\$b*\$b+\$a);» ),
create_function ( ‘$a,$b’ , ‘if ($a > 0 && $b != 0) )
);

echo «\nUsing the first array of dynamic functions\n» ;
echo «parameters: 2.3445, M_PI\n» ;
process ( 2.3445 , M_PI , $farr );

// now make a bunch of string processing functions
$garr = array(
create_function ( ‘$b,$a’ , ‘if (strncmp($a, $b, 3) == 0) return «** \»$a\» ‘ .
‘and \»$b\»\n** Look the same to me! (looking at the first 3 chars)»;’ ),
create_function ( ‘$a,$b’ , ‘return «CRCs: » . crc32($a) . «, «.crc32($b);’ ),
create_function ( ‘$a,$b’ , ‘return «similar(a,b) = » . similar_text($a, $b, $p) . «($p%)»;’ )
);
echo «\nUsing the second array of dynamic functions\n» ;
process ( «Twas brilling and the slithy toves» , «Twas the night» , $garr );
?>

Again, here is the same code using anonymous functions. Note that variable names in the code no longer need to be escaped, because they are not enclosed in a string.

function process ( $var1 , $var2 , $farr )
foreach ( $farr as $f ) echo $f ( $var1 , $var2 ) . «\n» ;
>
>

echo «\nUsing the first array of dynamic functions\n» ;
echo «parameters: 2.3445, M_PI\n» ;
process ( 2.3445 , M_PI , $farr );

// now make a bunch of string processing functions
$garr = array(
function( $b , $a ) < if ( strncmp ( $a , $b , 3 ) == 0 ) return "** \" $a \" " .
«and \» $b \»\n** Look the same to me! (looking at the first 3 chars)» ; >,
function( $a , $b ) < return "CRCs: " . crc32 ( $a ) . ", " . crc32 ( $b ); >,
function( $a , $b ) < return "similar(a,b) color: #007700">. similar_text ( $a , $b , $p ) . «( $p %)» ; >
);
echo «\nUsing the second array of dynamic functions\n» ;
process ( «Twas brilling and the slithy toves» , «Twas the night» , $garr );
?>

The above example will output:

Using the first array of dynamic functions parameters: 2.3445, M_PI some trig: -1.6291725057799 a hypotenuse: 3.9199852871011 b*a^2 = 4.8103313314525 min(b^2+a, a^2,b) = 8.6382729035898 ln(a)/b = 0.27122299212594 Using the second array of dynamic functions ** "Twas the night" and "Twas brilling and the slithy toves" ** Look the same to me! (looking at the first 3 chars) CRCs: 3569586014, 342550513 similar(a,b) = 11(45.833333333333%)

Example #3 Using dynamic functions as callback functions

Perhaps the most common use for dynamic functions is to pass them as callbacks, for example when using array_walk() or usort() .

$av = array( «the » , «a » , «that » , «this » );
array_walk ( $av , create_function ( ‘&$v,$k’ , ‘$v = $v . «mango»;’ ));
print_r ( $av );
?>

Источник

PHP Functions

PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute automatically 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

Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.

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

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

writeMsg(); // call the function
?>

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

familyName(«Jani»);
familyName(«Hege»);
familyName(«Stale»);
familyName(«Kai Jim»);
familyName(«Borge»);
?>

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

Example

function familyName($fname, $year) echo «$fname Refsnes. Born in $year
«;
>

familyName(«Hege», «1975»);
familyName(«Stale», «1978»);
familyName(«Kai Jim», «1983»);
?>

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 an error.

In PHP 7, type declarations were added. This gives us 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.

In the following example we try to send both a number and a string to the function without using strict :

Example

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
?>

To specify strict we need to set declare(strict_types=1); . This must be on the very first line of the PHP file.

In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:

Example

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
?>

The strict declaration forces things to be used in the intended way.

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

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

PHP Functions — Returning values

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

Example

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

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

Example

Passing Arguments by Reference

In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:

Example

Use a pass-by-reference argument to update a variable:

Источник

Оцените статью