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.
- class FileUpload
- {
-
- private $filepath; //Specify the path to save the file
- private $allowtype = array("gif", "jpg", "jpeg", "png"); //Allowed types
- private $maxsize = 1000000; //The file size allowed to be uploaded is 1M
- private $israndname = true; //Whether to rename the file
-
- function __construct($filepath, $allowtype, $maxsize, $israndname)
- {
- $this ->filepath = $filepath;
- $this->allowtype = $allowtype;
- $this->maxsize = $maxsize;
- $this->israndname = $israndname;
-
- var_dump($this);
- }
- }
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!
- class FileUpload
- {
-
- private $filepath;
- private $allowtype;
- private $maxsize;
- private $israndname;
-
- function __construct(
- $filepath = "/upload",
- $allowtype = array(" gif", "jpg", "jpeg", "png"),
- $maxsize = 1000000,
- $israndname = true)
-
- {
- $this->filepath = $filepath;
- $this->allowtype = $allowtype;
- $this->maxsize = $maxsize;
- $this->israndname = $israndname;
-
- var_dump($this);
- }
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:
- class FileUpload
- {
-
- private $filepath;
- private $allowtype;
- private $maxsize;
- private $israndname;
-
- function __construct($options=array([default value]))
- {
- // Parse the incoming array
- foreach($options as $key=>$value){
- $this->$key = $value;
- }
- }
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:
- $up = new $FileUpload(array(
- "filepath" => "/upload",
- "israndname" => false,
- "maxsize" => 2000000
- ));
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:
- foreach($options as $key=>$value){
- $key = strtolower($key);
-
- ...
- }
Copy code
At this point, our design has met the first three points in the "Friendliness Goal". The overall code is as follows:
- class FileUpload {
-
- private $filepath;
- private $allowtype;
- private $maxsize;
- private $israndname;
-
- function __construct($options=array(
- "$filepath" => "./" ,
- "$allowtype" => array("txt","jpg"),
- "$maxsize" => 1000000,
- "$israndname" => true
- )){
- //Parse the incoming Array
- foreach($options as $key=>$value){
- $key = strtolower($key);
- $this->$key = $value;
- }
- }
- }
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.
- foreach($options as $key=>$value){
- $key = strtolower($key);
- //Determine whether there is this variable in the class
- if(in_array($key, get_class_vars(get_class( $this)))) {
- $this->$key = $value;
- }else{ //Prompt for error location and parameters
- echo "Error when init class ".get_class($this)." with key: " .$key." in array !";
- exit;
- }
- }
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:
- class FileUpload {
-
- //Use lowercase for variable names
- private $filepath;
- private $allowtype;
- private $maxsize;
- private $israndname;
-
- //Assign default values in the constructor
- function __construct ($options=array(
- "$filepath" => "./",
- "$allowtype" => array("txt","jpg"),
- "$maxsize" => 1000000,
- " $israndname" => true
- )){
- //Parse the incoming array
- foreach($options as $key=>$value){
- $key = strtolower($key);
- //Determine whether the key is Declare in the class
- if(in_array($key, get_class_vars(get_class($this)))) {
- //Check whether the value meets the requirements
- if(checkValue($key,$value)) {
- $this-> $key = $value;
- } else {
- //Prompt for error location and parameters
- echo "Invalid value".$value."found when init class ".get_class($this)." with key: ".$key. " in array !";
- exit;
- }
- }else{
- //Prompt for error location and parameters
- echo "Error when init class ".get_class($this)." with key: ".$key." in array !";
- exit;
- }
- }
- }
-
- function checkValue{
- if(){
- ...
- return true;
- }
- return false;
- }
- }
-
Copy code
|