iSaumya iSaumya - 1 year ago 80
PHP Question

How to handle class variable without $this?

I'm making a WordPress plugin with OOP concept and I'm facing some wired issue.

First I have a

file where I have a class like this

include_once plugin_dir_path( __FILE__ ) . 'something.php';

class something {
//some var
public $a;
private function __construct() { {
//all of my wordpress hook calls are here

public function foo() {
$this->a = 55; // this is working fine and not giving any error

Now I have another php file which holds another class which I included in the

let's say the new file is

and here I have

class some {
//some variables
public $b, $c;

// now this this class when I'm doming
public function bar() {
$this->b =1; // this is giving me error saying this is not an object.

Now I have no idea why
is not working inside the else class. Also As these variables are not static variables, I really can't do
. So, I was hoping if anyone else can tell me a way to access non static variables inside the class without using

Real Problem Link:

In case the above example is not exactly clear to you, here is the link of my actual project in github where you can check the whole code to get the full pucture.

Github Repo Link:

Now here the main plugin file is where I'm including my other PHP files which handels seperate things.

Now as
is the main plugin file, all the
call gets handelled by the constructor of the class on this file.

Now within
file's class
is working fine.

But on my other files like where I have a class called
, when I'm trying access the
class variables by using
within the
class, it is throwing exception like this:

[06-Nov-2016 17:56:48 UTC] PHP Fatal error: Uncaught Error: Using $this when not in object context in /home/example/
Stack trace:
#0 /home/example/ AICP_ADMIN::click_limit_field(Array)
#1 /home/example/ do_settings_fields('aicp_settings', 'aicp_section')
#2 /home/example/ do_settings_sections('aicp_settings')
#3 /home/example/ AICP_ADMIN::admin_settings_page('')
#4 /home/example/ do_action('toplevel_page_a...')
#5 {main}
thrown in /home/example/ on line 184

So, I cannot use
approach inside the
class to access my variables and methods. So, I was wondering is there is any other way of handelling this without manking my variables a
variable and accessing them like

Thanks in advance.

Answer Source

I think, you must have instance of AICP_ADMIN in instead of string. So try something like

$aicpAdmin = new AICP_ADMIN;
add_action( 'admin_enqueue_scripts', array( $aicpAdmin, 'admin_scripts' ) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download