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
global
before the first time
it is used. - The
init
hook fires very early in page load, long before your
page.php
executes - Your
$newdb
variable is not declaredglobal
untilpage.php
- Thus, the variable is declared
global
after it has been used in
theinit
action, 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.