Home > Backend Development > PHP Tutorial > A friendly function parameter passing mode design in PHP

A friendly function parameter passing mode design in PHP

WBOY
Release: 2016-07-25 08:46:18
Original
1005 people have browsed it

PHP is a friendly function parameter passing mode design, friends in need can refer to it.


When there are many parameters that need to be passed in the constructor function of a class, programmers are prone to compilation errors due to the difficulty in remembering the order and writing of parameters when coding, or values ​​may be passed to wrong parameters (weakly typed language) Case.


Friendly functional design

When programmers instantiate a class, the parameters passed in should meet the following friendliness goals:
1. Able to pass in only some parameters
2. Ability to pass in parameters out of order
3. Can not distinguish between upper and lower case of parameters
4. Able to promptly and accurately prompt errors that occur when transferring parameters


Improve process Example 1 - Assigning default values ​​to member variables Please look at the following code. The default value of the function is assigned in the member variable. In this way, when only some parameters are passed in, the system will generate a notice, that is, the first of the "friendliness goals" is not met.
  1. class FileUpload
  2. {
  3. private $filepath; //Specify the path to save the file
  4. private $allowtype = array("gif", "jpg", "jpeg", "png"); //Allowed types
  5. private $maxsize = 1000000; //The file size allowed to be uploaded is 1M
  6. private $israndname = true; //Whether to rename the file
  7. function __construct($filepath, $allowtype, $maxsize, $israndname)
  8. {
  9. $this ->filepath = $filepath;
  10. $this->allowtype = $allowtype;
  11. $this->maxsize = $maxsize;
  12. $this->israndname = $israndname;
  13. var_dump($this);
  14. }
Copy code
Example 2 - Assigning default values ​​in the constructor

This time, in order to eliminate the notice in the above example, any number of parameters can be passed in, and default values ​​are used for parameters that are not passed in. Change the program to: set the default value in the constructor.

Another problem arises: when the programmer passes in the parameters ("/upload",array("jpg","gif"),false), that is, the programmer forgets to pass in the maxsize parameter, and the system will error. Assign false to maxsize instead of israndname. The system does not output any errors, leaving hidden dangers for subsequent work!

  1. class FileUpload
  2. {
  3. private $filepath;
  4. private $allowtype;
  5. private $maxsize;
  6. private $israndname;
  7. function __construct(
  8. $filepath = "/upload",
  9. $allowtype = array(" gif", "jpg", "jpeg", "png"),
  10. $maxsize = 1000000,
  11. $israndname = true)
  12. {
  13. $this->filepath = $filepath;
  14. $this->allowtype = $allowtype;
  15. $this->maxsize = $maxsize;
  16. $this->israndname = $israndname;
  17. var_dump($this);
  18. }
Copy code
Example 3 - Using arrays to encapsulate parameters

To solve the problem in Example 2, we can check the incoming value to prevent misaligned assignments (generally, we will check the incoming value anyway). However, this is not a solution to the problem, because the function we want to implement also allows programmers to pass values ​​out of order.

In weakly typed languages, this problem can be solved by using the particularity of arrays to encapsulate all passed parameters into arrays and save them in the form of key=>value pairs. Please see the following code:

  1. class FileUpload
  2. {
  3. private $filepath;
  4. private $allowtype;
  5. private $maxsize;
  6. private $israndname;
  7. function __construct($options=array([default value]))
  8. {
  9. // Parse the incoming array
  10. foreach($options as $key=>$value){
  11. $this->$key = $value;
  12. }
  13. }
Copy code

This solves the problem of the order of parameters passed in, and also solves the problem of only passing some parameters.

However, a new problem arises. At this time, the programmer needs to input an array as a parameter, as follows:

  1. $up = new $FileUpload(array(
  2. "filepath" => "/upload",
  3. "israndname" => false,
  4. "maxsize" => 2000000
  5. ));
Copy Code
Example 4 - Solving the case of parameters

After using an array to encapsulate parameters, the programmer needs to manually enter the name of the variable. This will lead to writing problems such as MaxSize, maxSize, maxsize due to different styles. To solve this problem, just use lowercase when declaring member variables. , and then add a line to the constructor:

  1. foreach($options as $key=>$value){
  2. $key = strtolower($key);
  3. ...
  4. }
Copy code

At this point, our design has met the first three points in the "Friendliness Goal". The overall code is as follows:

  1. class FileUpload {
  2. private $filepath;
  3. private $allowtype;
  4. private $maxsize;
  5. private $israndname;
  6. function __construct($options=array(
  7. "$filepath" => "./" ,
  8. "$allowtype" => array("txt","jpg"),
  9. "$maxsize" => 1000000,
  10. "$israndname" => true
  11. )){
  12. //Parse the incoming Array
  13. foreach($options as $key=>$value){
  14. $key = strtolower($key);
  15. $this->$key = $value;
  16. }
  17. }
  18. }
Copy code
Example 5 - Handling errors in incoming keys

In the above example, if the programmer passes in a parameter that does not exist in the class, the system will report an error. Here we have two solutions:
1. Ignore invalid parameters and only execute valid parameters
2. A friendly reminder that a certain parameter you passed in is invalid

Personally, I think that for the sake of the robustness of the program, erroneous code cannot be easily allowed to exist, so we choose the second option. We will give a friendly reminder of this error to the caller.

  1. foreach($options as $key=>$value){
  2. $key = strtolower($key);
  3. //Determine whether there is this variable in the class
  4. if(in_array($key, get_class_vars(get_class( $this)))) {
  5. $this->$key = $value;
  6. }else{ //Prompt for error location and parameters
  7. echo "Error when init class ".get_class($this)." with key: " .$key." in array !";
  8. exit;
  9. }
  10. }
Copy code
Example 6 - Check whether the incoming value is legal

At this point, the four expected goals have been achieved. In order to make the __construct() function reusable and can be directly pasted when used, we abstract the value check into a function. Please see the modified code:

  1. class FileUpload {
  2. //Use lowercase for variable names
  3. private $filepath;
  4. private $allowtype;
  5. private $maxsize;
  6. private $israndname;
  7. //Assign default values ​​in the constructor
  8. function __construct ($options=array(
  9. "$filepath" => "./",
  10. "$allowtype" => array("txt","jpg"),
  11. "$maxsize" => 1000000,
  12. " $israndname" => true
  13. )){
  14. //Parse the incoming array
  15. foreach($options as $key=>$value){
  16. $key = strtolower($key);
  17. //Determine whether the key is Declare in the class
  18. if(in_array($key, get_class_vars(get_class($this)))) {
  19. //Check whether the value meets the requirements
  20. if(checkValue($key,$value)) {
  21. $this-> $key = $value;
  22. } else {
  23. //Prompt for error location and parameters
  24. echo "Invalid value".$value."found when init class ".get_class($this)." with key: ".$key. " in array !";
  25. exit;
  26. }
  27. }else{
  28. //Prompt for error location and parameters
  29. echo "Error when init class ".get_class($this)." with key: ".$key." in array !";
  30. exit;
  31. }
  32. }
  33. }
  34. function checkValue{
  35. if(){
  36. ...
  37. return true;
  38. }
  39. return false;
  40. }
  41. }
Copy code
PHP


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