How do people usually turn mysqli results into objects?
I cannot find any examples with fetch_object() when using custom classes. Assume the following setup
class Test1 {
function __construct(array $data) { ... }
}
class Test2 {
function __construct(array $data) { ... }
}
Assume that I have multiple classes with the same constructors, how can I dynamically instantiate these classes?
I would imagine something like this:
function customQuery($query, $class) {
// Get some data by mysqli query, assume we get the data as $result object
...
// Now I would like to store the data in an array with instances of $class
$array = array();
while ($obj = $result->fetch_object($class, ???) {
$array[] = $obj;
}
// Return the array with instances of $class
return $array;
}
What do I use as arguments there for my question marks? I only know that both class constructors of Test1 and Test2 want an associative array as input (probably not the same length!).
In the end I simply want to do something like
$arr1 = customQuery('SELECT id, product FROM test1 LIMIT 10', 'Test1');
$arr2 = customQuery('SELECT id, name, address FROM test2 LIMIT 10', 'Test2');
Of course I would appreciate your input if you have better ideas to achieve my goal.
Take a look at "fetch_object'
You have a argument $class_name
From the docs: The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.
It will automaticly create an instance of the given class and it will set the properties. so no need to pass an array http://www.php.net/manual/en/mysqli-result.fetch-object.php
A bit more explanation,
The fetch_object just fills the private properties etc (PHP Magic... i don't like it).
If your object has required parameters in the constructor but you want to fetch it from the database the fetch_object lets you define arguments for the constructor so it can be constructed instead of throwing warnings/errors.
class Test {
private $title;
public function __construct($required) {
}
}
$mysql->fetch_object('Test'); //will trigger errors/warnings
$mysql->fetch_object('Test', array(null)); //won't
What you could do is simpel fetch an array and construct the object
function query($query, $class) {
$data = $query->fetch_assoc();
$instance = new $class($data);
return $instance;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With