Composer and PDO related issue


#1

Hello,
I am using Composer to autoload my custom classes in a project. Can anyone tell me why the code below does not work, instead it gives Fatal error: Class 'Person' not found?

    $sql = "select * from person";
    $persons = $dbh->query($sql)->fetchAll(PDO::FETCH_CLASS, 'Person');

And this on the otherhand works and does not give that error:

    $p = new Person();
    var_dump($p);

#2

Nevermind! Figured it out. Forgot to put namespace there.

Fix:

    $sql = "select * from person";
    $persons = $dbh->query($sql)->fetchAll(PDO::FETCH_CLASS, 'namespace\Person');

#3

Note, should you have a longer namespace, or need the class anyways, you could also use:

$persons = $dbh->query($sql)->fetchAll(PDO::FETCH_CLASS, Person::class);

#4

Nice one thanks!


#5

Actually Person::class version will work only when the calling class is in the same namespace as the Person class. Or am I wrong?


#6

Yes. If it's not in the same namespace, than you should have imported the namespace.


#7

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.