Home > Backend Development > PHP Tutorial > PHP Learning Guide-Chapter 8 (2)

PHP Learning Guide-Chapter 8 (2)

黄舟
Release: 2023-03-04 07:14:01
Original
933 people have browsed it

Purchase function skills

Now let’s take a look at some of the more magical properties of functions, including methods of using a variable number of parameters, methods of allowing functions to modify incoming variables, and methods of making functions become data Method used.

The content of this section is the most challenging section of this chapter. It is only suitable for programmers who are adventurous, curious or experienced.

Number of variable parameters

When calling the incoming function according to the situation, it is very useful to know the actual number of parameters. There are three possible ways to handle it in PHP, one of which can only be used in PHP4:

1. Define a function with default parameters. When the function omits any parameters in the call, it will use the default value instead and no warning message will be displayed.

2. Use array parameters to store these values. The calling program code is responsible for wrapping this array, and the function body must properly separate the data.

3. Use the variadic functions in PHP4 (func_num_args(), func_get_arg() and func_get_args()).

Default parameters

In order to define a function with preset parameters, just change the formal parameters into specified expressions. If the parameters in the actual call are less than the formal parameters in the definition, PHP will compare and match the formal parameters with the actual parameters until they are used up, and then use the preset specifications to fill in the remaining parameters.

For example, the variables in the following function are all defined with default values:

function tour_guide($city = “Gotham City”,

$desc = “vast metropolis”,

$how_many = “ Dozens",

$of_what = "costumed villains")

{

print("$city is a $desc filled with

$how_many of $of_what.< BR >");

}

tour_guide();

tour_guide("Chicago");

tour_guide("Chicago", "wonderful city");

tour_guide("Chicago", "wonderful city",

"teeming millions");

tour_guide(“Chicago”,“wonderful city”,

“teeming millions”,

“gruff people with hearts of

gold and hard-luck stories to tell”);

The browser will output results similar to the following, Line breaks in the sentence are determined by the browser used:

Gotham City is a great metropolis filled with dozens of costumed villains.

Chicago is a great metropolis filled with dozens of costumed villains.

Chicago is a wonderful city filled with dozens of costumed villains.

Chicago is a wonderful city filled with teeming millions of costumed villains.

Chicago is a wonderful city filled with teeming millions of gruff people whit hearts of gold and hard-luck stories to tell.

Default parameters The main limitation of is that the matching of actual parameters to formal parameters is determined by a sequential comparison of the two, on a first-come, first-served basis. Therefore, you cannot mess with the default parameter settings and end up with a lot of problems without realizing it.

Use arrays to replace multiple parameters

If you are not satisfied with the flexibility of multiple parameters, you can use arrays as a means of communication, which can bypass the entire parameter counting problem.

The following example uses this strategy, and also uses several small tricks, such as the ternary operator (introduced in Chapter 7) and associative arrays (mentioned irregularly in Chapter 6, in Chapter 11 It will be fully explained in the chapter):

function tour_brochure($info_array)

{

$city =

IsSet ($info_array[?city?])?

$info_array[?city?]: "Gotham City ";

$desc =

IsSet ($info_array[?city?])?

$info_array[?desc?]: "great metroprlis";

$how_many =

IsSet ($info_array[?how_many? ])?

$info_array[?how_many?]:"dozens";

$of_what

IsSet ($info_array[?of_what?])?

$info_array[?of_what?]:"costumed villains";

print(“$city is a $desc filled with

$how_many of $of_what.< BR >”);

}

This function checks the four characters that separate the incoming array parameter from a specific string. To compare different values, use the ternary conditional operator "?". The local variable is specified as the passed value (if it has been stored in the array), otherwise it is specified as the default value. Now, we try to call this function with two different arrays:

tur_brochure(array()); //Empty array

$tour_info =

aray(?city?=>?Cozumel?,

? desc?=>?destination getaway?,

'of_what'= >'sandy beaches');

tur_brochure($tour_info);

In this example, we first use an empty array (corresponding to no parameters) Call tour_brochure, and then call it with an array that stores three of the four possible associated values. Its browser output is:

Gotham City is a great metropolis filled with dozens of costumed villains.

Cozumel is a destination getaway filled with dozens of sandy beaches.

In both cases, the number of "dozens" is defaulted because neither array has anything stored in the "how_many" associated section.

Using multiple parameters in PHP4

Finally, PHP4 provides some functions that can retrieve the number and value of parameters in the function body. These functions are:

fnc_num_args() takes no parameters and returns The number of parameters passed in when calling this function.

fnc_get_arg() takes an integer parameter n and returns the nth parameter of the function call. Parameter counting starts from 0.

fnc_get_args() takes no parameters and returns an array containing all parameters of the function call. The array index starts from 0.

These three functions will all throw warning messages if they are called outside the function body. If the index used when calling is higher than the index of the last parameter passed in, func_get_arg() will also throw a warning.

If the user's function will use these function functions to decode parameters, you can make full use of the function calls mentioned here. PHP will not be affected by the fact that the actual parameters are more than the number of formal parameters in the definition. Complain. Users can define a function without parameters and then use this function to compare and match any function that is actually passed in.

For example, consider the following two function instances, each of which returns an array of passed arguments:

fnction args_as_array_1()

{

$arg_count = func_num_args();

$counter = 0;

$local_array = array();

wile($counter < $arg_count)

{

$local_array[$counter] =

fnc_get_arg($ary_counter);

$counter = $ Countr + 1;

}

RTURN ($ Local_array);

}

Fnction ARGS_AS_ARAY_2 () {

RTUN (FUNC_GET_ARGS ()); Use func_get_arg() to retrieve each individual argument, and use the result of func_num_args() to bound the loop so no more arguments are retrieved than were actually passed in. Each parameter is stored in an array, and the array is passed back. Wrapping such arguments is actually done by func_get_arps(), so the second version of this function is very short.

Here is another example. We rewrite the previous tour_guide() function, which uses multiple parameter functions to replace the default parameters:

fnction tour_guide_2()

{

$num_args=func_num_args() ;

$city = $num_args > 0 ?

fnc_get_arg(0): "Gotham City";

$desc = $num_args >1 ?

$desc = $num_args > 1 ?

fnc_get_arg( 1): "great metropolis";

$how_many = $num_args > 2 ?

fnc_get_arg(2): "dozens";

$of_what = $num_args > 3 ?

fnc_get_arg(3): "costumed" villains";

pint("$city is a $desc filled with

$how_many of $of_what. < BR >");

}

tur_guide2();

The above program code and defaults Parametric program codes have the same functions and effects, and are subject to the same restrictions. The parameters are passed in positionally, so there is no way to replace "costumed villains" with anything else, only "Gotham City" is used as the default value.

Call-by-value vs. call-by-reference

The default action of user-defined functions in PHP is "call-by-value" Value call)", which means that when a variable is passed to a function call, PHP makes a copy of the variable value and passes it to the function. Therefore, no matter what the function does, it cannot change the actual variables that appear in the function call. Although this behavior has advantages, it also has disadvantages. This is certainly a good approach when we just want to make use of the function's return value, but it can get in the way if modifying the passed-in variable is the actual goal.

The following will demonstrate the implementation of a rather inefficient subtraction example to implement call by value:

fnction my_subtract($numl,$num2)

{

i ($numl < $num2)

de ("Negative numbers are imaginary");

$return_result = 0;

wile($numl >$num2)

{

$numl = $numl – 1;

$return_result = $return_result + 1;

}

rturn($return_result);

}

$first_op = 493;

$second_op = 355;

$result1 = my_subtract($first_op,$second_op);

pint(“result 1 is $ result1< BR >”);

$result2 = my_subtract($first_op,$second_op);

Print(“result2 is $result2< BR >”);

That’s great, we saw the same subtraction of two The result will be the same:

rsult1 is 138

rsult2 is 138

Even if my_subtract changes the value of its formal parameter $numl, you will still get this result. The $numl variable is only stored in the actual parameter $first_op Just a copy of the value, so $first_op will not be affected.

Call-by-reference

PHP provides two different ways to make a function more capable of modifying parameters in its definition, or in a function call, also known as a call-by-reference.

If you want to define a function that directly operates on the incoming variables, you can add an "&" symbol in front of the formal parameters in the definition, as shown below:

fnction my_subtract_ref(&$numl,&$num2)

{

i($numl-<$num2)

de("Negative numbers are imaginary");

$return_result = 0;

wile($num1 >$num2)

{

$numl = $num1 – 1;

$return_result = $return_result + 1;

}

rturn($return_result);

}

$first_op = 493;

$second_op = 355;

$result1 = my _subtract_ref($first_op, $second_op);

pint(“result1 is $result1< BR >”);

$result2 = my_subtract_ref($first_op,$second_op);

pint(“result2 is $result2< ; BR >");

Now, if we perform the same subtraction call as before, we get this output:

rsult1 is 138

rsult1 is 0

This is because of the formal parameter $numl and the actual parameter $first_op refers to the same content, and modifying one is equivalent to modifying the other.
You can also force a function to pass parameters accordingly by adding the "&" symbol before the actual parameters (this is a feature that is gradually being phased out and may be removed in future PHP versions). In other words, you can use the original call function by value to get the action by reference, as follows:

$first_op = 493;

$second_op = 355;

$result1 = my_subtract(&$first_op,& $second_op);

Print(“result1 is $result1< BR >”);

$result2= my_subtract(&$first_op,&$second_op);

Print(“result2 is $result2< BR >” );

This time we got the following result:

rsult1 is 138

rsult1 is 0

For PHP4, variable parameters can also be used outside function calls. Generally speaking, assigning a variable reference (&$varname) to a variable causes the two variables to become aliases,
(i.e. doppelgangers) of each other, rather than being two different variables with the same value. For example:

$name_1 = "Manfred von Richtofen";

$name_2 = "Percy Blakeney";

$alias_1 = $name_1; //The variables have the same value

$alias_2=&$name_2; //The variables are the same

$alias_1 = "The Red Baron"; //The actual name has not changed

$alias_2 = "The Scarlet Pimpernel"; //It doesn't matter what it is anymore

Prnt("$alias_1 is $name_1< BR> ; ”);

Prnt(“$alias_2 is $name_2< BR >”);

The above program code will get browser output like this:

The Red Baron is Manfred von Richtofen

The Scarlet Pimpernel is The Scarlet Pimpernel

Variable function name

A very flexible technique in PHP is to use variables to replace the location where the user defines the function. That is, instead of typing the literal function name in the program code, you can type a variable starting with the "&" symbol, and the actual function called during execution depends on the string assigned to the variable. In a sense, this allows functions to be used as data. This technique may be familiar to C programmers, but also to beginners of any kind of Lisp language such as Scheme or Common Lisp.

For example, the following two function calls are completely equivalent:

function customized_greeting()

{

print(“You are being greeted in a customized way !< BR >”);

}

customized_greeting();

$my_greeting = 'customized_greeting';

$my_greeting();

The above code produces the same output:

You are being greeted in a customized way! in a customized way!

Because the function name is a string, it can also be used as a parameter of the function or returned as a function result.

Extended Example+

Let’s take a look at what kind of trouble you might encounter when using one of the more advanced features of functions, including using function names as function parameters.

Example 8-1 This example shows an extended example of the function. This function implements the function of replacing passwords. This is the most primitive password system, replacing letters with letters in the alphabet. Another letter to mess up the displayed information.

The following program code is longer and more advanced than any program code demonstrated so far in this book. For those who don't want to know the details, you can skip this code.

Example 8-1 Cryptozoological substitution

/*Part 1: cryptographic calculations and utility functions*/

function add 1 ($num)

{

return(($num+ 1)%26);

}

function sub_1($num)

{

return(($num+ 25)% 26);

}

function swap 2 ($num)

{

if($num % 2 = = 0)

return($num+ 1);

else

return($num - 1);

}

function swap 26($num)


{

return(25 - $num);

}

function lower letter($char string)

{

return(ord($char string) >=ord(‘a’))&&

(ord(&char string)< =ord(‘z’)));

}

function upper letter($char string)

{

return((ord($char string) >=ord(‘A’))&&

(ord($char string)< =ord(‘z’)));

}

/*第二部份:letter cipher函式 */

function letter cipher ($char string, $code func)

{

if!(upper letter($char string)||

lower letter ($char string)))

return($char string);

if(upper leter($char string))

$base num = ord(‘A’);

else

$base num = ord($char string) –

$base num);

return(chr($base num + 

($code func ($char num )

% 26)));

}

/*第三部份:主要string cipher 函式 */

function string cipher($message,$cipher func)

{

$coded message = ””;

$message length = strlen($message);

for($index= 0;

$index < $message length;

$index++)

$coded message .=

letter cipher ($message[$index],$cipher func);

return($coded message);

}

范例8-1共有三个部分。在第一部份中,我们定义了几个对数字0—25进行简单数字运算的函式,这些数字代表密码程序中的字母A—Z。函式add_1把给它的数字加1,以「26」为模数(仅意味着26以及超过26的数字会“绕回”到开头从「0」开始。0变成1 、 1变成2 、…、25变成0。Sub_1则是沿另一个方向转换数字,透过加上25(在这种模数算法中就等于减1),25变成24 、 24变成23 、… 、0变成25。Swap_2则是以成对的方式置换数字的位置(0到1 、1到0 、 2到3 、 3到2…等等),swap_26则把较高的数字和较低的数字地行对调置换(25到0 、0到25 、 24到1 、1到24…等等)。

所有这些函式都算是这个简易密码程序的基础。最后还有两个公用程序函式,用以测试字符是大写还是小写字母。

第二部分就是个letter_cipher()函式,并该函式的工作是取得第一部分中的一个算术函式,然后应用它来对简单字母进行编码。该函式会先测试它处理的字符串(其中只有单元一字符)是否为字母;如果不是,则按原样传回。如果字符是个字母,则可使用。Ord()的功用是将其转化为数字,然后减支适当的字母(a或A),以把数字限定到0—25之间。一旦位于这个范围内,就可以应用其名字以字符串方式传入的密码函式中,然后再把数字转换成字母,最后传回它。

最后,第三部分是string_cipher()函式,该函式带有一个字符串讯息,还有一个密码函式,它传回的是一个新字符串值,其值为透过函式进行编码的内容。这里用到一两个以前没见到的功能(其中包括字符串连接运算子「.=」,在第十章中会提到),这个函式从讯息字符串的字母逐一进行处理,建构出新字符串,并用新字母是对对照旧字母的数字表示应用了$cipher_func得到的结果,到这里你大概了解这些足够了。

下面,我们编写一些程序码测试string_cipher();

$originak = “My secret message is ABCDEFG”;

Print(“Original message is :$orginal< BR >”);

$coding_array = array(‘add_1’,

‘sub_1,

‘swap_2’,

‘swap_26’);

For($count = 0;

$count < sizeof($coding_array);

$coded_message = 

String_cipher($original,$code);

Print(“$code encoding is :$coded_message< BR >”);

}

这些测试程序码使用了预先定义的四个字母编码函式,把它们隐藏在一个阵列中,然后回圈遍巡该阵列,编码$original讯息,并输出显示编码后的版本。浏览器输出如下所示:

original message is: My secret message is ABCDEFG

add_1 encoding is :Nz tfdsfu nfttbhf jt BCDEFGH

sub_1 encoding is :Lx rdbqfs nfttbhf jt BADCFRH

swap_2 encoding is :Nz tfdqfs nfttbhf jt BADCFEH

swap_26 encoding is : Nb hvxivg nvhhztv rh ZYXWVUT

我们可以把这个函式做为资料的方法再深入一步,编写一个给序列中的讯息应用多个密码的函比。这个函式也使用了PHP4的可变参数型函式:

Function chained_code ($message)

{

/* 先取得反映定讯息,然后替编辑码函式名称找个任意数目。

Applies each encoding function to the previous result and returns its result. */

$argc = func_num_args();

$coded = $message;

For ($count = 1 ; $count<$argc;$count++)

{

$function_name = func_get_arg($count) ;

$coded =

String_cipher($coded,

$function_name);

}

Return($coded);

}

Chained_code() The first parameter should be a message string, followed by is any number of names corresponding to cryptographic functions. The encoded message is the result of applying the first encoding function to the message, then applying the second encoding function to the result, and so on. We can test this by using various combinations of predefined alphabetic encoding functions.

$tricky =

Chained_code($original,

'add_1''swap_26',

'add_1''swap_2');

Print("Tricky encoded version is $tricky< BR >");

$easy =

Chained_code($original,

'add_1','swap_26',

'swap_','sub_1',

'add_1', 'swap_2,'

'swap_26,''sub_1, ');

Print("Easy encoded version is $easy< BR >");

The result is:

Tricky encoded version is Ma guwjh muggysu qg YXWXUVS

Easy encoded version is My secret message is ABCDEFG

As you can see, the "tricky" message code is a combination of previous code, but does not exactly correspond to any single coding function. The "easy" encoding is a more complex combination of these functions, and the result is the original message... without any changes! (This is not because the key code is invalid, we just want readers to understand why this specific sequence of editing functions can return to the original starting message again.)

The purpose of the range shown in this little password script I want you to understand that although the password program is a little more complicated, it becomes quite simple because PHP supports using function names as function parameters.

Summary

Most PHP functionality exists in a large number of built-in functions, which are provided by PHP's open source development team. Each function should have a description (although some are brief) in the online manual at http://www.php.net.

You can also write your own function, which can then be accessed in the same way as the built-in functions. Functions are written in simple C-style syntax, as follows:

Function my_function ($argl,$arg2,…)

{

Statement1;

Statement2;



Return($value );

}

User-defined functions can use any PHP type parameter combination, and can also return any type of value. There is no need to declare the types of parameters and return values.

In PHP4, there is no difference between the number of function definitions and function calls, as long as each function called has been defined. No separate function declaration or prototyping is required. Variables specified within a function will be restricted to the function area unless a global declaration is used. Local variables can be declared static, which means they retain their values ​​between function calls.

The default action behavior of user-defined functions is "call_by_reference", which means that the function uses a copy of the parameters in operation, so the original variables cannot be modified in the function call. By adding an "&" before the parameter, you can force "call-by-reference", which can be used either on the defining side or on the calling side. PHP provides a variety of ways to make the number of parameters taken by a function variable. Finally, the function to be called can be determined at execution time by replacing the name of the user-defined function with a string variable, allowing the function to be treated as data and passed back and forth between other functions.

The above is the content of PHP Learning Guide - Chapter 8 (2). For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template