This is a variable scope, an pure PHP, problem at heart.
I didn’t close it because I am assuming that mistake is in turn due to a misunderstanding of the init hook, or hooks in general perhaps, which is WordPress specific.
- In PHP, a global must be declared
globalbefore the first time
it is used. - The
inithook fires very early in page load, long before your
page.phpexecutes - Your
$newdbvariable is not declaredglobaluntilpage.php - Thus, the variable is declared
globalafter it has been used in
theinitaction, and thus too late.
PHP executes line by line in sequence. Order matters. The order that hooks fire determines the order of the code in any of the “attached” functions.
To fix this, declare your variable global in the callback to the init action hook.
add_action('init','my_new_db');
function my_new_db(){
global $newdb;
$newdb = new wpdb( 'test', 'test', 'test', 'localhost');
$newdb->show_errors();
}
You will still need global $newdb; in your page.php file to access the global you’ve created. Don’t remove that.