Composer and PDO related issue

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();

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


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

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);

Nice one thanks!

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

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

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