Я использую несколько конструкций с этого сайта.
Я изменил его для своих нужд.
Я получаю фатальные ошибки:
Missing argument 3 for ChildClass::__construct2()
и цепочки ошибок …
Missing argument 4 for ChildClass::__construct2()
Missing argument 5 for ChildClass::__construct2()
Undefined variable: c
Undefined variable: d
И оба конструктора имеют часть идентичного кода. Как я могу выразить это в __construct?
$arr = array (
"key1" => "val1",
"key2" => "val2");
$demo = new Demo("stack", $arr );
class ParentClass {
function __construct($var1 = "1", $var2 = "2"){
// distinctly different code
}
}
class ChildClass extends ParentClass {
function __construct(){
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f='__construct'.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
function __construct1( $a, array $e ) {
$this->ex = $a;
$this->ex3 = $e['key1'];
$this->ex4 = $e['key2'];
}
function __construct2( $a, $b, $c, $d, array $e ) {
$this->ex = $a + 1 - $v + $c; //example
$this->ex2 = $d;
$this->ex3 = $e['key1'];
$this->ex4 = $e['key2'];
}
}
И оба конструктора имеют часть идентичного кода. Как я могу выразить это в __construct?
Благодарю.
Число, указанное после __construct, указывает, сколько параметров он будет исключать. Вы указали 2 после __construct, но вы даете ему 5 параметров, из-за которых он выдает ошибку. Измените 2 на 5. Также переименуйте __construct1 в __construct2 Используйте код ниже
$arr = array (
"key1" => "val1",
"key2" => "val2");
$demo = new Demo("stack", $arr );
class ParentClass {
function __construct($var1 = "1", $var2 = "2"){
// distinctly different code
}
}
class ChildClass extends ParentClass {
function __construct(){
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f='__construct'.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
function __construct2( $a, array $e ) {
$this->ex = $a;
$this->setE($e);
}
function __construct5( $a, $b, $c, $d, array $e ) {
$this->ex = $a + 1 - $v + $c; //example
$this->ex2 = $d;
$this->ex3 = $e['key1'];
$this->ex4 = $e['key2'];
}
}
Надеюсь, это поможет вам
Это потому что 2 в __construct2
говорит, что ожидает 2 параметра, но ожидает 5. Измените имя на __construct5
,
Чтобы поместить идентичный код в одно место, сделайте его отдельным методом, который будет вызываться из обоих конструкторов, полный код:
class ChildClass extends ParentClass {
function __construct(){
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f='__construct'.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
function __construct2( $a, array $e ) { // rename method: 1 => 2
$this->ex = $a;
$this->setE($e);
}
function __construct5( $a, $b, $c, $d, array $e ) { // rename method: 2 => 5
$this->ex = $a + 1 - $v + $c; //example
$this->ex2 = $d;
$this->setE($e);
}
private function setE(array $e) {
$this->ex3 = $e['key1'];
$this->ex4 = $e['key2'];
}
}