PHP Fatal error: Declaration of ... MySQLServer :: insert () must be compatible with ... Server :: insert () in /home/lfLvpx/prog.php on line 102

Why does this error occur, and how to correct it?

abstract class Server { public function __construct($token) { if ($token !== $_POST['crm_token']) { http_response_code(401); } else { $this->accept(); } } abstract protected function insert(); ... } class MySQLServer extends Server { protected function insert(mysqli $link, $table, array $required) { $fields = "`".implode("`, `", $required)."`"; $fields_num = count( $required ); $questions = str_repeat( "?,", $fields_num - 1 ) . "?"; $query = "INSERT INTO `$table` ($fields) VALUES ($questions)"; $data = []; foreach( $required as $field ){ $data[] = $_POST[$field]; } $stmt = mysqli_prepare($link, $query ); $types = str_repeat('s', $fields_num ); $stmt->bind_param( $types, ...$data ); $stmt->execute(); } } 
  • they say the function should be the same as in Server. Do you have the same? Take a look. Signature - Alexey Shimansky
  • And how to make any signature? - Timur Musharapov
  • write another method with a different name ... - Alexey Shimansky
  • I need to implement a variant of various inserts with a variable number of arguments. For this, that method and abstract :) - Timur Musharapov
  • one
    the only exception by signature if optional parameters are declared in the child class in the method, for example, the parent is abstract protected function prefixName($name); and child public function prefixName($name, $separator = ".") ..... but something tells me they all have to you - Alex Shimansky

1 answer 1

I can offer this option for PHP 5.6+

 <?php abstract class Server { public function __construct($token) { //... } abstract public function insert(...$params); } class MySQLServer extends Server { public function insert(...$params) { print_r($params); } } $server = new MySQLServer(); $server->insert(1,2,3); /** Вывод в консоли: Array ( [0] => 1 [1] => 2 [2] => 3 ) **/ 

However, I do not see any benefit in OOP, if in insert it is necessary to transfer the connection object to the database. The whole essence of OOP will be revealed if the object will store connection objects inside of itself, and give standardized methods to the outside. To implement something other than MySQLServer, you need a PDO.

  • And can you ... $ params pass the first argument? Type: insert(...$params, array $required) - Timur Musharapov
  • No, ... $ params always comes last. In addition, $ required will have to be described in an abstract function, which may impose restrictions. - ilyaplot