mymac1
December 7, 2019, 1:04pm
1
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.)
mymac1
December 7, 2019, 5:04pm
3
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.
rpkamp
December 7, 2019, 8:28pm
5
Did you run composer install
after modifying composer.json
? You need to do that in order to update the autoloader with your custom configuration.
mymac1
December 8, 2019, 1:57pm
6
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?
rpkamp
December 8, 2019, 2:32pm
7
<?php
namespace Fontana\PolisCarHire;
use PDO;
class MyPDO extends PDO // line 4
{
public function __construct
rpkamp
December 8, 2019, 2:37pm
8
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
system
Closed
March 9, 2020, 12:50pm
10
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.