php - Why does using $this inside a class in a Wordpress plugin throw a fatal error? -


i'm in process of writing wordpress plugin creates page in admin area, executing frontend code.

the code below throws nice fatal error: using $this when not in object context error. rather mystifying, variable called inside class.

maybe i'm not following intended wordpress plugin structure functions , classes, conceptual code below created using relevant entries on plugin development in wordpress codex.

could explain why error triggered, because when create instance of class outside of wordpress codebase 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 have fixed it, going basics , asking google humble question: "using classes in wordpress plugins".

both article jay fortner , 1 on dconstructing.com helpful.

basically, i'm calling add_menu_page , add_submenu_page within class. under impression functions somehow created object, don't.

my code looks , i'm able call declared class variable without error:

if (!class_exists("myclass")) {   class myclass {     var $test = 'test variable';      function __construct() {       add_action('admin_menu', 'my_plugin_menu');     }      function my_plugin_menu() {       add_menu_page('my plugin', 'my plugin', 'manage_options', 'my-plugin', array(&$this, 'index'));       add_submenu_page('my-plugin', 'add new thing', 'add new', 'manage_options', 'my-plugin-add', array(&$this, 'add'));     }      public function index() {       //index code     }      public function add() {       echo $this->test;     }   }   new myclass; } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -