class upload{
protected $name;
protected $sex;
public function __construct($name='默认值',$sex='默认值'){
$this->name=$name;
$this->sex=$sex;
}
}
Why can’t it be written like this?
public function __construct($name,$sex){
$this->name=$name;
$this->sex=$sex;
}
Can I also write like this? If there are too many parameters above, what year, horse and month should be written?
public function __construct($opt){
$this->name=$opt->name;
$this->sex=$opt->sex;
}
Why must you add a default value to the constructor, otherwise an error will be reported! ! ! I'm used to writing js, so I don't understand the constructor of php a bit. Explain, is it necessary to assign default values to parameters?
天蓬老师2017-05-16 12:04:46
Has nothing to do with constructors.
As long as the parameters of the function are not given default values, you must pass the parameters when using it.
It is not right to say that it is more troublesome than js. In js (before ES6), setting default values for functions is more troublesome than php; so what can I say?
In addition, the third method you mentioned is to pass an object or an array as a parameter. This approach is okay; of course, you can use a loop when assigning values instead of writing them one by one.
黄舟2017-05-16 12:04:46
1. You don’t need to give a default value. The error you reported here should be because your first parameter was given a default value. Parameters with default values should be placed at the back, according to the grammar regulations. (For details, please refer to the document)
2. Pass in Of course the object is also possible
大家讲道理2017-05-16 12:04:46
This has nothing to do with the constructor
If you don’t pass parameters when defining the function, an error will be reported
function a($name,$age = 1)
{
}
$name
must be passed, $age
is not required. $name
必传,$age
不用。
至于为什么,PHP语法规定
As for why, PHP syntax regulations
The PHP syntax does not report an error. Try running it. If PHP reports an error, post the error message
某草草2017-05-16 12:04:46
If the PHP function is explicitly specified and the parameters are not given default values, the parameters must be passed when calling. If there is a default value, you can read the default value without passing parameters when calling.
If you find it troublesome to pass parameters explicitly, you can use the func_get_args() function to read the parameters.
After PHP5.6, you can also use the function A(...$args) form to read parameters.
巴扎黑2017-05-16 12:04:46
The constructor is the function called by default when you create a new object
The parameters of the function must be passed if there is no default value. This is a grammatical rule
All functions are like this. No matter how many parameters you have, you have to pass them one by one
All the languages I know have this rule