PHP mysqli_result: Use Traversable interface with fetch_object

后端 未结 3 1247
青春惊慌失措
青春惊慌失措 2021-01-13 16:11

the PHP mysqli_result class implements the Traversable interface for some time now. This gives some interesting possibilities like the following piece of code:



        
3条回答
  •  执笔经年
    2021-01-13 16:32

    As I stated in the comments, it's easy to do exactly what you want with PDO. Just set the PDO::ATTR_DEFAULT_FETCH_MODE attribute, and it will do the appropriate kind of fetch when you do the foreach loop.

    You can also set the PDO::ATTR_STATEMENT_CLASS attribute to define the class to use.

    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS);
    $pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS,array('classname',$constructorArgs));
    

    See http://php.net/manual/en/pdo.setattribute.php for more info.

    With that solution, you'd need to change the ATTR_STATEMENT_CLASS attribute for each query, depending on what class you want to instantiate.

    Alternatively, you can set it to specify the classname within the query:

    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
    $stmt = $db->query("SELECT 'classname', * FROM `table` WHERE `id` = 1;");
    

    Simply add the relevant classname to your query as the first field to be selected.

    See one of the answers on this related question In PHP, How do I set default PDO Fetch Class? for more on this.

提交回复
热议问题