Referring to an array inside a PHP Object while defining the object
I have this object definition
return (object) [
// the database information
'db_info' => [
'type' => 'mysql',
'server' => 'localhost',
'database' => 'myshop',
'username' => 'root',
'password' => 'password',
'tableprefix' => 'password',
'charset' => 'password'
],
// the database tables
'tables_info' => [
'tblcountries' => db_info.database . '.'. db_info.tableprefix . 'countries',
'tblsettings' => db_info.database . '.'. db_info.tableprefix . 'settings'
]
]
I am trying to use some of the array defined inside the same object
that is in the tables_info array
'tblcountries' => db_info.database . '.'. db_info.tableprefix . 'countries`
Is it possible, if yes how..
Solution 1:
You can do that in 2 steps like this
$obj = (object) [
'db_info' => [
'type' => 'mysql',
'server' => 'localhost',
'database' => 'myshop',
'username' => 'root',
'password' => 'password',
'tableprefix' => 'password',
'charset' => 'password'
]
];
$obj->table_info = [
'tblcountries' => $obj->db_info['database'] . '.' . $obj->db_info['tableprefix'] . 'countries',
'tblsettings' => $obj->db_info['database'] . '.'. $obj->db_info['tableprefix'] . 'settings'
];
print_r($obj);
RESULT
stdClass Object
(
[db_info] => Array
(
[type] => mysql
[server] => localhost
[database] => myshop
[username] => root
[password] => password
[tableprefix] => password
[charset] => password
)
[table_info] => Array
(
[tblcountries] => myshop.passwordcountries
[tblsettings] => myshop.passwordsettings
)
)
Or if you wanted everything to be an object rather that an object with arrays in
$obj = (object) [
'db_info' => (object) [
'type' => 'mysql',
'server' => 'localhost',
'database' => 'myshop',
'username' => 'root',
'password' => 'password',
'tableprefix' => 'password',
'charset' => 'password'
]
];
$obj->table_info = (object) [
'tblcountries' => $obj->db_info->database . '.' . $obj->db_info->tableprefix . 'countries',
'tblsettings' => $obj->db_info->database . '.'. $obj->db_info->tableprefix . 'settings'
];
print_r($obj);
RESULT
stdClass Object
(
[db_info] => stdClass Object
(
[type] => mysql
[server] => localhost
[database] => myshop
[username] => root
[password] => password
[tableprefix] => password
[charset] => password
)
[table_info] => stdClass Object
(
[tblcountries] => myshop.passwordcountries
[tblsettings] => myshop.passwordsettings
)
)