I guess I have a problem understanding inheritance.
I have 4 classes like so;
class FOO extends WP_Widget {
protected $pluginOptions;
function __construct() {
$this->pluginOptions = get_option('option_name',0);
/*$this->pluginOptions['email'] returns /is set to email@domain.com here*/
}
}
class FOO_ACTIONS extends FOO {
function __construct() {
parent::__construct();
/*some actions*/
}
/*some methods*/
}
class FOO_SEND_EMAIL extends FOO_ACTIONS {
function __construct() {
parent::__construct();
/*some actions*/
}
/*some methods*/
}
class BAR extends FOO{
function __construct() {
/*change email here */
$this->pluginOptions['email']='anotheremail@anotherdomain.com';
}
}
$BAR=new BAR();
in another file i am calling:
$sendEmail=new FOO_SEND_EMAIL;
I thought that – as BAR
gets called before FOO_SEND_EMAIL
$this->pluginOptions['email']
is now anotheremail@anotherdomain.com
.
However, when doing $sendEmail
it is still set to email@domain.com
. can anyone point me in the right direction perhaps as to where I’m going wrong here? (happy to provide more code of course if necessary).
If you call
BAR
the e-mail address is set toanotheremail@anotherdomain.com
. But when you callFOO_SEND_EMAIL
, the e-mail address is set toemail@domain.com
because it is overwritten byFOO
‘s constructor.You run
$sendEmail = new FOO_SEND_EMAIL
, when you do this the constructor ofFOO
is called. It has nothing to do with whatever$BAR
currently is.$pluginOptions
is object property. It is not static property, so you set it’s value for one instance of this class (object) and not for all of them. Every object has it’s own value of this property/member.You should use static property to do what you want, I guess.
same boat, nine months later. WordPress⦠hmph…
In widgets.php, there is a class called WP_Widget_Factory (line 319), in itâs constructor, it attaches _register_widgets to the widgets_init hook. This callback function, in all it’s great wisdom, then decides to iterate through the array of registered widgets and any that are already registered, it deletes (line 341), so it can re-register them, calling the constructor __construct, directly (line 345, 324).
Also, none of this matters as your parent constructor is never being called in BAR’s constructor anywayz. In php, if you define __construct(), you have to EXPLICITLY call parent::__construct(); to get the parent constructor to run.
However, if you DON’T define __constuct() the parent constructor will run by default.
Basic rules of inheritance that.