PDO::FETCH_CLASS with multiple classes

后端 未结 4 1300
春和景丽
春和景丽 2021-01-29 02:35

I am trying to turn an query result into classes.

$result->setFetchMode(PDO::FETCH_CLASS, \'myclass\', array());

This works quite well howev

4条回答
  •  天涯浪人
    2021-01-29 03:10

    I would not use PDO::FETCH_CLASS for that. You can change your SQL to return class name based on value of age

    SELECT 
    id,
    name,
    age,
    CASE WHEN age < 21 THEN 'child'
    ELSE 'adult' END
    AS class_name
    FROM SOME_TABLE";
    
    Then use your PDO::FETCH_ASSOC as fetch type
    Then when you loop over your results
    you can easily instantiave class based on
    $result['class_name'] like this:
    $class = $result['class_name'];
    $obj = new $class;
    

提交回复
热议问题