In a repetitive structure are there differences between working with Object or Array?

Asked

Viewed 116 times

5

When I do a query in the database by PHP and want to return this data with while, usually use the fetch_object(), which returns the data in type object.

For example:

$query = "SELECT * FROM TABELA";
$exect = $conn->query($query);

while($row = $exect->fetch_object()){
    echo $row->coluna.'<br>';
}

But I used to fetch_array() for data return.

$query = "SELECT * FROM TABELA";
$exect = $conn->query($query);

while($row = $exect->fetch_array()){
    echo $row['coluna'].'<br>';
}

In these two cases some questions arise:

1 - Has difference in performance?

2 - Has usability difference?

  • 1

    What you mean by usability?

  • Easily use array object or item in methods, functions... so I don’t know. KKK

  • I think you mean readability nay?

  • 1

    Is also part.

  • 1

    http://stackoverflow.com/questions/124240/mysql-results-in-php-arrays-or-objects

1 answer

2


Essentially the difference is in the type of data that will be returned even. Use whatever is most convenient for your style or need.

The fetch_array will obviously return a array which can be accessed by index or name of the fields (keys) or by the two. This is defined in the parameter resulttype and standard is access by both forms.

The fetch_object can be accessed with the members access syntax of an object. It can popular an object of a specific class. Can be passed as parameter.

In terms of performance they are essentially equivalent, because there are no actual objects in PHP, they are arrays Associative underneath the cloths. Since it is an extra abstraction layer it is likely to be slightly slower, but the difference will be tiny.

Of course there may be other problems with the fetch_object, after all it will convert the contents of the key to a PHP identifier. There are rules of what may be contained in the identifiers. What happens if you have an unsuitable character for PHP in the name of the database field? You have to protect yourself from this with {} and the syntax gets worse.

If you want to automate members' access through variables you will also have to use this resource on the objects. It is more natural to use the array that works best with variables to indicate the key/index to be accessed. This is a very common pattern of who knows how to make optimized codes, follow the dry principle and likes to make language work for him and not him work for language.

Some people think that turning everything into an object is easier to work with, but they don’t know that deep down they’re not adding any advantage, or performance, or organization, anything, it’s just taste. So choose one or the other for the taste.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.