KunLun
KunLun

Reputation: 3225

ArgumentCountError when fetch_object with value for class_name parameter

I have an project(directory) test in xampp/htdocs.

In this project I have 2 php files(Account.php and 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 = '[email protected]';");

        if($result) {

            $obj = $result->fetch_object("Account"); //ArgumentCountError

            if ($obj instanceof Account) {

                printf($obj->email);

            }

        }

    }

}

(new Test())->index();

I run this in browser via: http://localhost/test/test.php and I get an error.

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

If I remove parameter from fetch_object("Account") -> fetch_object(), there is no longer error and works. But I want to use it with parameter.

Why with parameter generate error and how to fix it?

My PHP version is 7.4

Upvotes: 1

Views: 241

Answers (1)

u_mulder
u_mulder

Reputation: 54841

As the manual says:

Note that mysqli_fetch_object() sets the properties of the object before calling the object constructor.

But from the same manual you can see that there's a third parameter:

An optional array of parameters to pass to the constructor for class_name objects.

So, you should do something like this:

$obj = $result->fetch_object("Account", ['email', 'pass', 'id']);

If this does not help, you either should make all constructor arguments optional:

function __construct(string $email = '', string $pass = '', int $id = 0)

as fetch_object already sets these props. This also means that you should check whether these arguments empty or not.

Or use not fetch_object but something else and just call the constructor explicitly, but that's obvoiusly the last solution, that you want to use.

Upvotes: 1

Related Questions