问题
I am trying to use PDO::FETCH_CLASS on an object. I am using namespacing and just entering:
$result = $query->fetchAll(\PDO::FETCH_CLASS, 'Product');
or
$result = $query->fetchAll(\PDO::FETCH_CLASS, '\Product');
results in PHP looking for Product.php
in the root of the app.
I can successfully instantiate a new Product though using:
$product = new Product();
So I know my name spacing is working.
Is this not possible? Or do I need to instantiate a Product first then populate it after from the query?
回答1:
I'd suspect PDO does not look up aliased class names or resolve the current namespace. So you have to pass it explicitely:
= $query->fetchAll(\PDO::FETCH_CLASS, __NAMESPACE__ . '\\Product');
Exactness nitpick: Note that while a single backslash does work, in single quotes it is intended to escape literal single quotes and itself.
来源:https://stackoverflow.com/questions/7914914/pdo-fetch-class-and-namespacing-issue