简体   繁体   中英

PHP arrays and objects together - Bad / Good Practice?

I'm fetching data from a MySQL Database. The results are returned in an object.

I can then access the data like so:

$db_data->row

In a foreach loop I alter the $db_data by adding an array, for example:

foreach ($db_data as $data) $db_data->row->new_data = array('key' => 'value');

Now the new data can be accessed with:

$db_data->row->new_data['key']

Is this good or bad practice?

If it's generally considered bad practice , what would be the right way to go to alter the database object?


EDIT:

According to the comments I want to clarify the question:

I don't want to change the data in the database. What I'm doing here is adding data to the object returned by the database class in my php app (Laravel 4 btw.) .

So my question is all about throwing objects together with arrays and if it's good or bad practice .

As a personal opinion i don't see why it would be a bad practice.
In my view it's a natural thing you do depending on your program,
and it's not really causing confusion.

A thing that you should keep note of is that you can do $var["key a"] but you can't do $obj->key a

To me it sounds like you are storing data in a php serialized object written to a field in a database table.

If so this makes it just about impossible to access the values from that data without getting the record and unserializing it first. Somewhat defeats the point of using a relational database.

from my side as i see
there is nothing wrong with what you are doing
i dont consider it as a bad practice

i just think that if you know what are you doing and you will get the result that you want
never care about how are you doing it, just do it ... ^_^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM