PHP: Cast array to class

raw

config-array-to-class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
//config as array: easy to write
$configArray = [
    'debug' => true,
    'dsn' => 'mysql://user:pass@host',
];
 
//config class: nice for static analysis with phpstan
class Config
{
    /**
     * @var bool
     */
    public $debug;
    
    /**
     * @var string
     */
    public $dsn;
}
 
//cast an array with all data into an object of our Config class
$configObject = unserialize(
    preg_replace(
        '#^O:8:"stdClass":#',
        'O:6:"Config":',
        serialize((object) $configArray)
    )
);
var_dump($configObject);
 
Christian Weiske Christian Weiske
owner

History