我在xampp/htdocs中有一个项目(目录)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
发布于 2020-03-24 09:07:43
如手册所述:
注意,
mysqli_fetch_object()在调用对象构造函数之前设置对象的属性。
但是从同一手册你可以看到有一个第三参数
传递给class_name对象构造函数的可选参数数组。
所以,你应该这样做:
$obj = $result->fetch_object("Account", ['email', 'pass', 'id']);如果这没有帮助,您应该让所有构造函数参数都是可选的:
function __construct(string $email = '', string $pass = '', int $id = 0)因为fetch_object已经设置了这些道具。这也意味着您应该检查这些参数是否为空。
或者不是使用fetch_object,而是使用其他东西,只需显式调用构造函数,但这显然是您想要使用的最后一个解决方案。
https://stackoverflow.com/questions/60827790
复制相似问题