I'm learning to create a WP plugin as a class. However, it seems the add_action doesn't work when calling my function; it works when using $this->init().
Example:
class test
{
public $age = NULL;
public function __construct()
{
//register an activation hook
register_activation_hook( __FILE__, array( &$this, 'installplugin' ) );
add_action('init', array( &$this, 'init' ) ); //this doesn't work
//$this->init(); //This WORKS!
}
function installplugin()
{
add_option( 'age', 45 );
$this->init();
}
function init()
{
$age = get_option( 'age' );
$this->age = $age;
}
function printAge( )
{
echo "The age is " . $this->age . "<br />";
}
}
So, after running:
$learnObj = new learnable_test();
$learnObj->printAge();
It only prints: "The age is "
But if I were t comment out the add_action('init',...) and use the $this->init(), that seems to work, printing "The age is 45"
What am I missing?
$learnObj->printAge();
'init' action was already done, aren't you?$learnObj = new learnable_test();
?after_setup_theme
hook are done. If this is a plugin (and so it seems) you can replaceadd_action('init'
withadd_action('plugins_loaded'
that is performed before. Better you can:$learnObj = new learnable_test( get_option('age') );
and in the classpublic function __construct($age) { $this->age = $age;
. Doing so init method is not needed...&$this
unless you're stuck in a time machine.