Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Unable to set parameter `options` when creating PDO object from config object

As Phalcon\Config converts all arrays to objects Phalcon\Config, so we can't use key options in this case. Just getting this error: TypeError: PDO::__construct() expects parameter 4 to be array, object given

I think it should be fixed.

P.S. I'm using Phalcon 4.

Can you show us how are you setting the connection?

Sample code i have been using for a while:

        $di->setShared('db', function() use ($databaseCredentials) {
            return new \Phalcon\Db\Adapter\Pdo\Mysql([
                'host' => $databaseCredentials->host,
                'username' => $databaseCredentials->username,
                'password' => $databaseCredentials->password,
                'dbname' => $databaseCredentials->name,
                'charset' => 'utf8',
                'options'  => [
                    \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8, CHARACTER SET utf8;',
                    \PDO::ATTR_PERSISTENT => true,
                    \PDO::ATTR_STRINGIFY_FETCHES => false

Your code works because you use an array as config. In my case i use config object:

$config = \Phalcon\Config([
   'database' => [
      'adapter' => 'Mysql',
      'host' => 'localhost',
      'username' => 'user',
      'password' => 'pass',
      'dbname' => 'db_name,
      'charset' => 'utf8mb4',
      'options' => [],

   function() use ($config) {
      return new \Phalcon\Db\Adapter\Pdo\Mysql((array) $config->database);

As we see, i should use the trick (array) $config->database which converts object to array, but it doesn't converts nested arrays. My miss when created this post, here is a little bit another problem.

I don't remember where i've found such method, i tried this few years ago with Phalcon 3 and now came back to Phalcon, but now it is version 4 :)

I think all config parameters should be in a separate file, we should prevent to set it in working scripts. I can use recursive converting, but i'm not sure it is the right way.


There is method toArray()

That works, thank you.