我有一个项目(目录)test。xampp/htdocs
在这个项目中,我有 2 个 php 文件(Account.php 和 Test.php)。
//---Account.php---
<?php
class Account{
protected int $id;
protected string $email;
protected string $pass;
function __construct(string $email, string $pass, int $id = 0) {
$this->id = $id;
$this->email = $email;
$this->pass = $pass;
}
}
//---Test.php---
<?php
require_once("Account.php");
class Test{
public function index(){
$hostname="localhost";
$database="mydb";
$username="root";
$password="";
$mysqli = new mysqli($hostname, $username, $password, $database);
$result = $mysqli->query("SELECT * FROM accounts WHERE email = 'my@email.com';");
if($result) {
$obj = $result->fetch_object("Account"); //ArgumentCountError
if ($obj instanceof Account) {
printf($obj->email);
}
}
}
}
(new Test())->index();
我在浏览器中通过:运行它http://localhost/test/test.php,我得到一个错误。
Fatal error:
Uncaught ArgumentCountError: Too few arguments to function Account::__construct(),
0 passed and at least 2 expected in C:\xampp\htdocs\test\Account.php:9
Stack trace:
#0 [internal function]: Account->__construct()
#1 C:\xampp\htdocs\test\Test.php(19): mysqli_result->fetch_object('Account')
#2 C:\xampp\htdocs\test\Test.php(33): Test->index()
#3 {main} thrown in C:\xampp\htdocs\test\Account.php on line 9
如果我从中删除参数fetch_object("Account") -> fetch_object(),则不再有错误并且可以工作。但我想将它与参数一起使用。
为什么使用参数会产生错误以及如何解决?
我的 PHP 版本是 7.4
慕丝7291255