I try to clone a PDO instance using $pdo2 = clone $pdo
, but I get unexpected behaviour in some PHP versions:
Here is a code that reproduces the problem:
$pdo1 = new \PDO('sqlite::memory:');
$pdo1->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
echo "PDO 1 is OK\n";
$pdo2 = clone $pdo1;
$pdo2->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
echo "PDO 2 is OK\n";
echo $pdo1->getAttribute(\PDO::ATTR_ERRMODE) === $pdo2->getAttribute(\PDO::ATTR_ERRMODE)
? "❌ The attribute IS changed\n"
: "✅ The attribute IS NOT changed\n";
Is there any way to make an independent copy of a PDO object or at least copy only the DSN, username and password?
Why I need to clone a PDO instance: I need to keep a PDO instance isolated to reach goals:
There is no way to clone a PDO object safely. You should never have such an idea, as it makes no sense:
So if you want an isolated PDO instance, just create it.