gpt4 book ai didi

php - 在我自己的类中使用 mysqli_result::fetch_object 不起作用

转载 作者:行者123 更新时间:2023-12-04 17:01:52 24 4
gpt4 key购买 nike

我将尝试使用 fetch_object('Classname') 来测试这个方法。

Inserent.php 中的类 Inserent:

namespace classes\model;

class Inserent{
private $nummer;
private $nickname;
private $email;

public function __construct ($nummer, $nickname, $email){
$this->nummer = $nummer;
$this->nickname = $nickname;
$this->email = $email;
}

public function getNummer(){
return $this->nummer;
}

public function setNummer($nummer){
$this->nummer = $nummer;
}
...
}

使用在 Mapper-Class InserentDAO.php 中:
namespace classes\mapper;
use classes\model\Inserent;

class InserentDAO{
private $dbConnect;

public function __construct (){
$this->dbConnect = MySQLDatabase::getInstance();
}

public function readAll(){
$sql = "SELECT inserentennummer, nickname, email FROM inserent";
$inserent = null;
$inserentList = array();

if ($result = $this->dbConnect->query($sql)) {

while ($inserent = $result->fetch_object('classes\model\Inserent')) {
$inserentList[] = $inserent;
}
$result->close();
}
return $inserentList;
}
...
}

我收到错误并且我的对象是空的:

Warning: Missing argument 1 for classes\model\Inserent::__construct() in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on line 10

Warning: Missing argument 2 for classes\model\Inserent::__construct() in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on line 10

Warning: Missing argument 3 for classes\model\Inserent::__construct() in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on line 10

Notice: Undefined variable: nummer in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on line 11

Notice: Undefined variable: nickname in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on line 12

Notice: Undefined variable: email in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on line 13



但是如果我在 Mapper 中更改代码,它将起作用。

部分代码 InserentDAO.php 代替:
while ($obj = $result->fetch_object()) {
$inserent = new Inserent($obj->inserentennummer, $obj->nickname, $obj->email);
$inserentList[] = $inserent;
}

最佳答案

我相信fetch_object调用一个空的构造函数,然后根据它获取的结果列设置属性。 There is a comment on the manual confirming that.

所以这就是fetch_object("classes\model\Inserent")是在做:

$object = new classes\model\Inserent();
$object->inserentennummer = $result['inserentennumer'];
$object->nickname = $result['nickname'];
$object->email = $result['email'];
return $object;

这就是为什么它提示缺少参数和 undefined variable (它们是 private )。

显而易见的解决方案是重构您的类以提供一个空的构造函数和公共(public)属性:
namespace classes\model;

class Inserent{
public $nummer;
public $nickname;
public $email;

public function __construct ($nummer = 0, $nickname = "", $email = ""){
//...

使属性公开的另一种方法是使用 __set 魔术方法,但您仍然必须提供零参数构造函数。

关于php - 在我自己的类中使用 mysqli_result::fetch_object 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49777989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com