Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

PHP Programming/Functions

From Wikibooks, open books for an open world
<PHP Programming
The foreach LoopPHP Programming
Functions
PHP Include Files

Introduction

[edit |edit source]

Functions (ormethods in the context of a class/object) are a way to group common tasks or calculations to be re-used simply.

Functions in computer programming are much like mathematical functions: You can give the function values to work with and get a result without having to do any calculations yourself.

You can also find a huge list of predefined functions built into PHP in thePHP Manual's function reference.

How to call a function

[edit |edit source]

Note thatecho is not a function.[1]"Calling a function" means causing a particular function to run at a particular point in the script. The basic ways to call a function include:

  • calling the function to write on a new line (such as after a ";" or "}")
print('I am human, I am.');
  • calling the function to write on a new line inside a control
if($a==72){print('I am human, I am.');}
  • assigning the returned value of a function to a variable "$var = function()"
$result=sum($a,5);
  • calling a function inside the argument parentheses (expression) of a control
while($i<count($one)){}

In our earlier examples we have called several functions. Most commonly we have called the functionprint() to print text to the output. The parameter for echo has been the string we wanted printed (for exampleprint("Hello World!") prints "Hello World!" to the output).

If the function returns some information, we assign it to a variable with a simple assignment operator "=":

$var1=func_name();

Parameters

[edit |edit source]

Parameters are variables that exist only within that function. They are provided by the programmer when the function is called and the function can read and change them locally (except for reference type variables that are changed globally, which is a more advanced topic).

When declaring or calling a function that has more than one parameter, you need to separate between different parameters with a comma ','.

A function declaration can look like this:

functionprint_two_strings($var1,$var2){echo$var1;echo"\n";echo$var2;returnNULL;}

To call this function, you must give the parameters a value. It doesn't matter what the value is, as long as there is one:

print_two_strings("Hello","World");

Output:

HelloWorld

When declaring a function, you sometimes want to have the freedom not to use all the parameters. Therefore, PHP allows you to give them default values when declaring the function:

functionprint_two_strings($var1="Hello World",$var2="I'm Learning PHP"){echo($var1);echo("\n");echo($var2);}

These values will only be used, if the function call does not include enough parameters. If there is only one parameter provided, then$var2 = "I'm Learning PHP":

print_two_strings("Hello");

Output:

HelloI'm Learning PHP

Another way to have a dynamic number of parameters is to use PHP's built-infunc_num_args,func_get_args, andfunc_get_arg functions.

functionmean(){$sum=0;$param_count=func_num_args();for($i=0;$i<$param_count;$i++){$sum+=func_get_arg($i);}$mean=$sum/$param_count;echo"Mean:{$mean}";returnNULL;}

or

functionmean(){$sum=0;$vars=func_get_args();for($i=0;$i<count($vars);$i++){$sum+=$vars[$i];}$mean=$sum/count($vars);echo"Mean:{$mean}";returnNULL;}

The above functions would calculate thearithmetic mean of all of the values passed to them and output it. The difference is that the first function usesfunc_num_args andfunc_get_arg, while the second usesfunc_get_args to load the parameters into an array. The output for both of them would be the same. For example:

mean(35,43,3);

Output:

Mean: 27

Returning a value

[edit |edit source]

This function is all well and good, but usually you will want your function to return some information. Generally there are two reasons why a programmer would want information from a function:

  1. The function does tasks such as calculations, and we need the result.
  2. A function can return a value to indicate, if the function encountered any errors.

To return a value from a function use thereturn() statement in the function.

functionadd_numbers($var1=0,$var2=0,$var3=0){$var4=$var1+$var2+$var3;return$var4;}


Example PHP script:

functionadd_numbers($var1=0,$var2=0,$var3=0){$var4=$var1+$var2+$var3;return$var4;}$sum=add_numbers(1,6,9);echo"The result of 1 + 6 + 9 is{$sum}";

Result:

The result of 1 + 6 + 9 is 16

Notice that areturn() statement ends the function's course. If anything appears in a function declaration after thereturn() statement is executed, it is parsed but not executed. This can come in handy in some cases. For example:

functiondivide($dividee,$divider){if($divider==0){// Can't divide by 0.returnfalse;}$result=$dividee/$divider;return$result;}

Notice that there is noelse after theif. This is due to the fact that, if$divider does equal0, thereturn() statement is executed and the function stops.

If you want to return multiple variables, you need to return an array rather than a single variable. For example:

functionmaths($input1,$input2){$total=($input1+$input2);$difference=($input1-$input2);$return=array("tot"=>$total,"diff"=>$difference);return$return;}

When calling this from your script, you need to call it into an array. For example:

$return=maths(10,5);

In this case$return['tot'] will be the total (e.g. 15), while$return['diff'] will be the difference (5).

Runtime function usage

[edit |edit source]

A developer can create functions inside a PHP script without having to use thefunction name($param...) {} syntax. This can be done by way of programming that can let you run functions dynamically.

Executing a function that is based on a variable's name

[edit |edit source]

There are two ways to do it: either using the direct call, or thecall_user_func or thecall_user_func_array:

Usingcall_user_func* functions to call functions

[edit |edit source]

call_user_func andcall_user_func_array only differ in that thecall_user_func_array allows you to use the second parameter as array to pass the data very easily, andcall_user_func has an infinite number of parameters that is not very useful in a professional way.In these examples, a class will be used for a wider range of using the example:

classSome_Class{functionmy_function($text1,$text2,$text3){$return=$text1."\n\n".$text2."\n\n".$text3;return$return;}}$my_class=newSome_Class();

Usingcall_user_func:

$one="One";$two="Two";$three="Three";$callback_func=array(&$my_class,"my_function");$result=call_user_func($callback_func,$one,$two,$three);echo$result;

Usingcall_user_func_array:

$one="One";$two="Two";$three="Three";$callback_func=array(&$my_class,"my_function");$result=call_user_func_array($callback_func,array($one,$two,$three));echo$result;

Note howcall_user_func andcall_user_func_array are used in both of the examples.call_user_func_array allows the script to execute the function more dynamically.

As there was no example of using both of these functions for a non-class function, here they are:

Usingcall_user_func:

$one="One";$two="Two";$three="Three";$callback_func="my_function";$result=call_user_func($callback_func,$one,$two,$three);echo$result;

Usingcall_user_func_array:

$one="One";$two="Two";$three="Three";$callback_func="my_function";$result=call_user_func_array($callback_func,array($one,$two,$three));echo$result;

More complicated examples

[edit |edit source]
$my_func($param1,$param2);$my_class_name=newClassObject();$my_class_name->$my_func_from_that_class($param1,$param2);// The -> symbol is a minus sign follow by a "larger than" sign. It allows you to// use a function that is defined in a different PHP class. It comes directly from// object-oriented programming. Via a constructor, a function of that class is// executable. This specific example is a function that returns no values.call_user_func($my_func,$param1,$param2);call_user_func(array(&${$my_class_name},$my_func),$param1,$param2);// Prefixing a & to a variable that represents a class object allows you to send the// class object as a reference instead of a copy of the object. In this example this// means that $my_class_name Object would have a copy made of it, the function will// act on the copy, and when the function ends. The original object wouldn't suffer// modifications. Passing an object through its reference passes the address in memory// where that object is stored and call_user_func will alter the actual object.call_user_func_array($my_func,array($param1,$param2));// Most powerful, dynamic examplecall_user_func_array(array(&${$my_class_name},$my_func),array($param1,$param2));
functionpositif($x+$y;){$x=2;$y=5;$z=$x+$y;echo$z;}positif=$x+$y;

Creating runtime functions

[edit |edit source]

Creating runtime functions is a very good way of making the script more dynamic:

$function_name=create_function('$one, $two','return $one + $two;');echo$function_name."\n\n";echo$function_name("1.5","2");

create_function creates a function with parameters$one and$two, with a code to evaluate return…Whencreate_function is executed, it stores the function's info in the memory and returns the function's name. This means that you cannot customise the name of the function although that would be preferred by most developers.

Citations

[edit |edit source]
  1. echo


The foreach LoopPHP Programming
Functions
PHP Include Files
Retrieved from "https://en.wikibooks.org/w/index.php?title=PHP_Programming/Functions&oldid=4342487"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp