I am trying composer autoload but error above

Fatal error : Class ‘Fontana\PolisCarHire\PDO’ not found in F:\htdocs_xampp\PDO_www.poliscarhire.com\src\MyPDO.php on line 4

I am trying composer autoload but error above, how to include PDO in the composer autoload

index.php

<?php
require_once('vendor/autoload.php');

try{
  $db = new Fontana\PolisCarHire\MyPDO();
  
  $mysecuredata = 150;

  $sql = 'SELECT name, color, calories FROM fruit ORDER BY name';

  foreach ($db->query($sql) as $row) {
      print $row['name'] . "\t";
      print $row['color'] . "\t";
      print $row['calories'] . "\n<br>";

composer.json


{
    "license": "MIT",
    "require": {
        "php": "^7.2"
    },
    "require-dev": {
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "Fontana\\PolisCarHire\\": "src/"
        }
    }
}

src/MyPDO.php

<?php
namespace Fontana\PolisCarHire;

class MyPDO extends PDO  // line 4
{
    public function __construct

(Preface: I don’t know composer. My knowledge for this post derives from the following link:)

According to the above page, you’ve forgotten to tell your index page to Import the namespace. (Step “e” under using PSR-4 in the above link.)

how import with “use …” a build-in library like PDO…?

Well you’re not using a built in library; you wrote your own class. So now you have to import the namespace of the class you created.

Did you run composer install after modifying composer.json? You need to do that in order to update the autoloader with your custom configuration.

class MyPDO extends PDO  
{
    public function __construct

PDO is a SPL class i think included in 5.6, 7.x PHP
The code works using PDO extends my class WITHOUT composer and namespaces

How use PDO with composer and namespaces?

<?php
namespace Fontana\PolisCarHire;

use PDO;

class MyPDO extends PDO  // line 4
{
    public function __construct

I would however like to add that instead of extending PDO, you can create a lot more flexible design if you instead create class that accepts a PDO instance as constructor argument.

1 Like

yes thank you worked

I used the

<?php use PDO;