OOPHP - How to create multiple objects from an array of database rows?

I am new to “object oriented” PHP, but so far I have managed to deal with most. I create a website where users can register an account and then add, say, hobbies to their profile.

I was able to determine the creation of a class, an object, saving one user in the database and extracting one user from the database - creating a new object from an associative array, which is returned from SQL "select", a request.

Where am I stuck now, when I need to return multiple rows (records) from the database. For example, a user may have 7 hobbies; The SQL query returns all 7 rows to an associative array (with fields, for example, hobby_id, hobby_name, hobby_created), but how can I make each of these row / hobby entries into my own object?

I tried looking for all kinds of terms, but I don’t know if I will just miss the buzz word I need to find. If anyone could, please let me know how best to do this, I will be forever magnificent.

Thanks a lot Steve

+3
source share
5 answers

When you have a lot of hobbies, create hobby objects in foreach.

$hobby = Array();
foreach ($query->results as $row)
  $hobby = new Hobby($row['person_id'], $row['hobby']...

or perhaps a hash of objects.

+1

, , PDO, :

$stmt->fetchAll( PDO::FETCH_CLASS, 'Hobby' );

.

http://www.php.net/manual/en/pdostatement.fetch.php

PDO:: FETCH_CLASS: , . fetch_style PDO:: FETCH_CLASSTYPE (, PDO:: FETCH_CLASS | PDO:: FETCH_CLASSTYPE), .

: fetch(), fetchAll(), setFetchMode() fetch()

$stmt->setFetchMode( PDO::FETCH_CLASS, 'Hobby' );
+3

. Acme OOP . , (, ) . , , , hobbie .

0

, ? , /. , , , / . - , ? , Hobby .

0

, :

// $obj is instance of stdClass
$obj = (object)array('hobby_name'=>'name');

, , , ( @Galean).

0

Source: https://habr.com/ru/post/1768916/


All Articles