I’m in the process of writing a WordPress plugin which creates a page in the admin area, as well as executing some frontend code.
The code below throws a nice Fatal error: Using $this when not in object context
error. Which is rather mystifying, as the variable is called inside the class.
Maybe I’m not following the intended WordPress plugin structure for functions and classes, but the conceptual code below was created using the relevant entries on plugin development in the WordPress Codex.
Could somebody explain why the error is triggered, because when I create an instance of the class outside of the WordPress codebase everything is fine.
if (!class_exists("MyClass")) {
class MyClass {
var $test = 'Test variable';
public function index() {
//Index code
}
public function add() {
echo $this->test;
}
}
}
add_action('admin_menu', 'my_plugin_menu');
function my_plugin_menu() {
add_menu_page('My Plugin', 'My Plugin', 'manage_options', 'my-plugin', array('MyClass', 'index'));
add_submenu_page('my-plugin', 'Add New Thing', 'Add New', 'manage_options', 'my-plugin-add', array('MyClass', 'add'));
}
So, I’ve seem to have fixed it, by going back to the basics and asking Google the humble question: “Using classes in WordPress plugins”.
Both the article by Jay Fortner and one on dConstructing.com were helpful.
Basically, I’m now calling add_menu_page and add_submenu_page from within the class. I was under the impression those functions somehow created an object, but they obviously don’t.
My code now looks something like this and I’m able to call the declared class variable without error:
This is no longer true.
From: https://codex.wordpress.org/Function_Reference/do_action_ref_array
Or
What you should do is the following:
Using
array('MyClass', 'index')
cause php to execute the method as a static methed, but passing an actual object as the first argument will call the method via the object.Would also work if you want to reuse the object.
depends how the class is being called, statically Class::method() will throw errors. If that is the case i think you need to use self::$test; but could be wrong.