var_dump of result gives null value. But deeper in

2020-04-17 06:53发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
New Mysqli Object is Null

I just started with building my database class for my MVC framework. While building this I am experimenting with simple queries and tables in order to make it work properly.

I was trying to query the following:

SELECT * FROM mvc_test

This should return 3 rows:

1 | test

2 | test2

3 | test3

I use the following method to query:

<?php $this->result = $this->conn->query($this->q); ?>

Where $this->conn is:

<?php 
 $this->conn = new mysqli($this->reg->conf->database['host'],
 $this->reg->conf->database['user'],
 $this->reg->conf->database['password'],
 $this->reg->conf->database['database']);
?>

Where $this->reg->conf->database contains all the values for host, database etc. This works, I have a connection.

Now, when I var_dump the result like this:

<?php var_dump($this->result); ?>

I get this:

object(mysqli_result)[9]

public 'current_field' => null

public 'field_count' => null

public 'lengths' => null

public 'num_rows' => null

public 'type' => null

But, as said before it should contain at least 3 rows, so I would expect num_rows to be '3'.

Now, when I var_dump the num_rows of the result like this:

<?php var_dump($this->result->num_rows); ?>

I get a 'int 3' as response.

Conclusion: in the first var_dump it's null, but with a deeper inspection I get a 3. So it reads 3 rows. When I add another row (the 4th), it returns a 4 as expected.

My question is: why is the var_dump not working properly? Why Does it say null at first, but with a deeper inspection it does have a value.

Thanks in advance, I'm really struggling with this one since I don't get any errors as well.

回答1:

The object is implemented "lazily", i.e. it does not retrieve data from the server until it's actually required (i.e. you access something from the result object).

var_dump doesn't seem to trigger the property getters so they are shown as null.