I register class methods for actions in my WordPress plugin. When my method gets called by WordPress, if I try to use the $this variable, php throws an error saying the call to $this variable is illegal outside the context of an object.
How can that be? I thought unless the method is static, you’re not supposed to be able to call class methods if the class isn’t instantiated! My method isn’t static! What is happening?
The source code
Obviously the initialize is called from the main plugin file:
add_action('init', array('AffiliateMarketting', 'initialize'), 1);
My class looks like this:
class AffiliateMarketting
{
public function __construct()
{
// some initialization code
}
public function initialize()
{
add_action('woocommerce_before_single_product', array("AffiliateMarketting", "handleAffiliateReferral"));
}
public function handleAffiliateReferral($post)
{
$this->xxx(); // <---- offending function call
}
public function xxx()
{
}
}
The received error message is in fact Fatal error: Using $this when not in object context in <filename> on line <linenumber>
.
You have to instantiate the class first. Something like this:
and then do the following:
Edit: forgot to add, your action in your method should be added like this:
You’re not supposed to be. That’s why you’re getting an error.
I don’t know exactly how you’re registering the method (code would help), but probably, you’re expecting WordPress to take care of creating an instance, but that’s not its role.
I found thought the Codex documented if the class name is specified using its string representation, then the
add_action
function will assume the call is to a static method.On the other hand if and instance of the class is passed along then
add_action
will use that instance to make the method call.Although Arman hasn’t specified which php version he is using, I would assume it’s probably 5.3.2 or 5.3.3. The error itself is rather similar to the one described in this question and the solution also would be to upgrade to the latest version of php 5.3.