PHP Learning Book-the eighth chapter (II)

Source: Internet
Author: User
Tags modulus
Input function Tips

Now let's look at some of the more magical properties of the function, including the method of using the variable number of arguments, the method that allows the function to modify the incoming variable, and the legal side that makes the function the data used.

This section is one of the most challenging sections of this chapter, and it is only suitable for adventurous, highly inquisitive or experienced programmers.

Number of variable parameters

It is useful to know the actual number of parameters when calling an incoming function according to the situation, and there are three possible ways to handle it in PHP, one of which can only be used in PHP4:

1. Defines a function with a preset parameter that, when a function misses any parameter in a call, replaces it with a preset value and does not display a warning message.

2. These values are stored using array parameters, which are responsible for wrapping the array in the calling code, and the function ontology must separate the data in it appropriately.

3. Use variable parameter functions in PHP4 (Func_num_args (), Func_get_arg (), and Func_get_args ()).

Preset parameters

To define a function with a preset parameter, simply turn the formal parameter into the specified expression. If the actual call parameter is less than the formal parameter when it is defined, PHP will match the formal parameter with the actual parameter until it is exhausted, and then use the preset designation to fill the remaining parameters.

For example, the variables in the following function are defined with a preset value:

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 outputs a result similar to the following, and the line break symbol in the sentence is determined by the browser used:

Gotham City was 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 .

The main limitation of the preset parameters is that the match of the actual parameter to the formal parameter is determined by the sequence of the two, first-come-first service. Therefore, the default parameters can not be used to set up, so that a lot of problems at the end without knowing.

Replacing multiple parameters with an array

If you are not satisfied with the elasticity of multiple parameters, you can use the array as a means of communication, which bypasses the whole parameter counting problem.

The following example uses this strategy and also uses a few tricks, such as the ternary operator (introduced in the seventh chapter) and the associative array (which is not included in chapter sixth, which is fully explained in chapter 11th):

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 to compare the passed array parameters to four different values separated by a particular string, using the ternary conditional operator "? , the zone variable is specified as an incoming value (if it is already stored in the array), or it is specified as a preset value. Now, let's try calling 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 call Tour_brochure with an empty array (corresponding to no parameters) and then call it with an array that stores three of the four possible associated values in the array. Its browser output is:

Gotham City was 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 preset, because neither array has any content stored in the "how_many" Association section.

Using multiple parameters in PHP4

Finally, PHP4 provides some functions to regain the number and value of parameters within the function body, which are:

Fnc_num_args () returns the number of arguments passed in when calling the function without parameters.

Fnc_get_arg () takes an integer parameter N and returns the nth parameter of the function call. The parameter count starts at 0.

Fnc_get_args () returns an array with no parameters, which contains all the parameters of the function call, and the array index starts at 0.

If you call them outside the function body, the three functions will throw out a warning message, and Func_get_arg () will throw a warning if the index used for the call is higher than the last parameter index passed in.

If the user's function uses these functions to decode parameters, you can take advantage of the reference to the function call here, PHP will not because the actual parameters than the formal parameters in the definition of the number of complaints. The user can define a function without parameters, and then use this function to match any actual incoming function.

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

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 = $counter + 1;

}

Rturn ($local _array);

}

Fnction args_as_array_2 ()

{

Rtun (Func_get_args ());

}

The first cumbersome function uses Func_get_arg () to retrieve each individual parameter and uses the result of Func_num_args () to delimit the bounds, so the retrieved parameters are no more than the actual incoming. Each parameter is stored in the array and biographies the array back. Wrapping such parameters is actually done by Func_get_arps (), so the second version of the function is short.

Here is another example where we rewrite the previous tour_guide () function, which uses multiple parameter functions to replace the preset 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 program code above is the same as the function and effect of the preset parameter shape, and is subject to the same limitation. Parameters are passed in by location, so there is no way to replace "costumed villains" with other content, only with "gotham city" as the default.

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

The default action for a user-defined function in PHP is "call by value (Call-by-value call)", which means that when a variable is passed to a function call, PHP makes a copy of the value and passes it on to the function. Therefore, no matter what the function does, it cannot change the actual variables that appear in the function call. This behavior is good, but it has disadvantages. This is certainly a good way to use the return value of a function, but it can be a hindrance if you modify the incoming variable to be the actual target.

Here's an example of a fairly inefficient subtraction instance of an application that calls by value:

Fnction my_subtract ($NUML, $num 2)

{

I ($numl < $num 2)

De ("Negative numbers is imaginary");

$return _result = 0;

Wile ($numl > $num 2)

{

$NUML = $numl –1;

$return _result = $return _result + 1;

}

Rturn ($return _result);

}

$first _op = 493;

$second _op = 355;

$result 1 = my_subtract ($first _op, $second _op);

Pint ("Result1 is $result 1< BR >");

$result 2 = my_subtract ($first _op, $second _op);

Print ("Result2 is $result 2< BR >");

That's good, we saw the same subtraction two times the result would be the same:

RSULT1 is 138

RSULT2 is 138

Even if my_subtract changes the value of its formal parameter $numl, the result will be that the $NUML variable only holds a copy of the value in the actual parameter $first_op, so $first_op will not be affected.

Follow the lead call (Call-by-reference)

PHP provides two different ways to make a function in a definition, or in a function call, to have the ability to modify a parameter, also known as a call-to-address.

If you want to define a function that operates directly on an incoming variable, you can precede the formal argument with a "&" symbol in the definition as follows:

Fnction my_subtract_ref (& $numl,& $num 2)

{

I ($numl-< $num 2)

De ("Negative numbers is imaginary");

$return _result = 0;

Wile ($num 1 > $num 2)

{

$NUML = $num 1–1;

$return _result = $return _result + 1;

}

Rturn ($return _result);

}

$first _op = 493;

$second _op = 355;

$result 1 = My _subtract_ref ($first _op, $second _op);

Pint ("Result1 is $result 1< BR >");

$result 2 = my_subtract_ref ($first _op, $second _op);

Pint ("Result2 is $result 2< BR >");

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

RSULT1 is 138

RSULT1 is 0

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

$first _op = 493;

$second _op = 355;

$result 1 = my_subtract (& $first _op,& $second _op);

Print ("RESULT1 is $result 1< BR >");

$result 2= my_subtract (& $first _op,& $second _op);

Print ("Result2 is $result 2< BR >");

This time again the following results were obtained:

RSULT1 is 138

RSULT1 is 0

For PHP4, variable parameters can also be used outside of a function call. In general, assigning a variable parameter (& $varname) to a variable causes the two variables to be aliases to each other.
Instead of two different variables with the same value. For example:

$name _1 = "Manfred von Richtofen";

$name _2 = "Percy Blakeney";

$alias _1 = $name _1;//variable with the same value

$alias _2=& $name _2;//variable

$alias _1 = "the Red Baron";//The actual name has not changed

$alias _2 = "the Scarlet Pimpernel";//whatever it is doesn't matter anymore.

Prnt ("$alias _1 is $name _1< br>");

Prnt ("$alias _2 is $name _2< BR >");

The above code will get a 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 replace the position of the user-defined function with a variable. That is, instead of typing the literal function name in the code, you can type a variable that starts with the "&" symbol, and the function that is actually called at execution time depends on the string assigned to the variable. In a sense, this allows the function to be used as data. This technique may be familiar to the input C language programmer, as is the case for beginners of any kind of Lisp language (such as scheme or Common Lisp).

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

function customized_greeting ()

{

Print ("Being greeted in a customized-!< BR >");

}

Customized_greeting ();

$my _greeting = ' customized_greeting ';

$my _greeting ();

The above code produces the same output:

You is being greeted in a customized!

You is being greeted in a customized!

Because the function name is a string, it can also be used as a function parameter, or as a function result to be passed back.

Extended Expansion Example +

Let's look at what kind of trouble you'll encounter with a more advanced feature of the function, including using the function name as a function parameter.

Example 8-1 shows an extended example of a function that accomplishes a replacement password, which is the most primitive cipher system that replaces another letter with one of the letters in the alphabet to confuse the display of information.

The code below is considered to be the longer and more advanced of any program code shown so far in this book. For those who do not want to know the details, you can skip this program code.

Example 8-1 Secret replacement

/* Part I: Cryptographic calculus and tool letters */

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 ($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 '))) ;

}

/* Part Two: letter cipher function */

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)));

}

/* Part III: MAIN string cipher function */

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);

}

Example 8-1 has a total of three sections. In the first part, we define a few functions that perform simple numeric operations on the number 0-25, which represent a A-Z of the letters in the cipher program. The function Add_1 adds 1 to its number, with "26" as modulus (meaning that 26 and more than 26 of the numbers "go around" to the beginning from "0". 0 becomes 1, 1 becomes 2 、...、 25 becomes 0. Sub_1 is the conversion of the number in another direction, by adding 25 (which equals minus 1 in this modulus algorithm), 25 becoming 24, 24 becoming a 、... 、 0 becomes 25. Swap_2 is the placement of numbers in a paired way (0 to 1, 1 to 0, 2 to 3, 3 to 2 ...). And so on), swap_26 the higher numbers and lower numbers to the replacement (25 to 0, 0 to 25, 24 to 1, 1 to 24 ...). And so on).

All of these functions are the basis of this simple cryptographic procedure. Finally, there are two utility functions to test whether the characters are uppercase or lowercase letters.

The second part is a letter_cipher () function, and the function is to get an arithmetic function in the first part, and then apply it to encode the simple letters. The function tests whether the string it handles (where only the cell character) is a letter, and if not, returns it as-is. If the character is a letter, you can use it. The function of Ord () is to convert it to a number and then subtract the appropriate letter (a or a) to limit the number to 0-25. Once within this range, you can apply a cryptographic function whose name is passed in as a string, and then convert the number to a letter, and then return it.

Finally, the third part is the String_cipher () function, which has a string message and a cryptographic function that returns a new string value whose value is the content encoded through the function. Here are one or two previously not seen features (including string connection operator ".=", which is mentioned in the tenth chapter), this function is processed from the letter of the message string, constructs a new string, and uses the new letter to control the number of the old letter to indicate that the $cipher_func obtained results are applied, You probably know enough about this here.

Below, we write some program code test 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 >");

}

These test codes use a pre-defined four-letter coded function that hides them in an array, loops through the array, encodes the $original message, and outputs the encoded version. The browser output looks like this:

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

We can take this function as a data method and go one step further and write a function that applies multiple passwords to the messages in the sequence. This function also uses the PHP4 variable-parameter function:

Function Chained_code ($message)

{

/* Obtain a reflection message first, and then find an arbitrary number for the edit code function name.

Each coded function is applied on the previous result, and then the result is returned. */

$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);

}

The first argument to Chained_code () should be a message string followed by any number of names corresponding to the cryptographic function. The encoded message is the result of applying the first coded function to the message, and then the result is applied to the second coded function, and so on. We can test it by using a variety of combinations of pre-defined letter-coded 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 was My secret message is ABCDEFG

As you can see, the "tricky" message is a combination of the previous code, but does not exactly correspond to any single coded function. and "easy" coding is a more complex combination of these functions, resulting in the original message ... There is no change! (This is not because the key code is invalid, we just want to let the reader figure out why this particular edit function sequence can return to the original message again.) )

The purpose of this little code script is to let you know that although the cipher program is a little more complicated, it becomes quite simple because PHP supports the use of function names as function parameters.

Summary

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

You can also write your own function, which can then be used in the same way as the built-in function. The function is written in a simple C-language style syntax, as follows:

Function my_function ($argl, $arg 2,...)

{

Statement1;

Statement2;

...

Return ($value);

}

A user-defined function can use any type of PHP parameter mate, or return any type of value. And there is no need to declare the type of the parameter and the callback value.

In PHP4, there is no difference in the number of functions defined and functions called, as long as each function of the call was once defined. It is not necessary for a separate function declaration or a prototype design. The variable specified in the function is limited to that function area unless the global declaration is used. Zone variables can be declared static, which means that they can retain their values between function calls.

The default action behavior of a consumer-defined function is "call by Value (Call_by_reference)", which means that the function uses a copy of the parameter in its operation, so the original variable cannot be modified in a function call. By adding a "&" to the parameter, you can force a "push-to-call (Call-by-reference)", either in the defined party, or in conjunction with the calling party. PHP provides several ways to change the number of arguments that a function takes. Finally, the function to be called can be determined at the execution time, substituting a string variable for the name of the user-defined function, allowing the function to be treated as data and passing it back and forth between other functions.

The above is the PHP learning treasure-the eighth chapter (ii) of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.