4

I have a class (yii2 widget) that has private properties and public static functions. When I try to access a private property from the static method like $this->MyPrivateVar an error is generated regarding that I don't have to use $this in non object context! The following is a snippet of my code:

class JuiThemeSelectWidget extends Widget { private $list; private $script; private $juiThemeSelectId = 'AASDD5'; public $label; .... public static function createSelectList($items) { $t = $this->juiThemeSelectId; ... } 

I tried the following, but it seems that undergoes to infinite loop Maximum execution time of 50 seconds exceeded!

public static function createSelectList($items) { $t = new JuiThemeSelectWidget; $juiThemeSelectId = $t->juiThemeSelectId; ... } 

So how could I access the private juiThemeSelectId from the static method?

2
  • Is $items a Widget class? Commented Jan 24, 2015 at 23:28
  • No, it is just a parameter passed to the method from another method. @CommuSoft Commented Jan 24, 2015 at 23:29

2 Answers 2

5

The sort answer is: You can't access a non-static property in a static method. You don't have access to $this in a static method.

What you could do is just to change the property to static like:

private static $juiThemeSelectId = 'AASDD5'; 

And then access it with this:

echo self::$juiThemeSelectId; 

For more information about the keyword static see the manual: http://php.net/manual/en/language.oop5.static.php

And a quote from there:

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

Sign up to request clarification or add additional context in comments.

4 Comments

As you said, I set the property to be private static and then I tried to access it from the public static method as $t = self::$juiThemeSelectId; but it gives the error: Getting unknown property: common\libs\JuiThemeSelectWidget::juiThemeSelectId
@sємsєм Can you please how the code which you use now to get this error.
Sorry, your solution works fine, I just forgot that I called it in another line as $this.
@sємsєм No problem, glade that i could help you!
0

you can access it using self:

public static function createSelectList($items) { $t = self::juiThemeSelectId; ... } 

2 Comments

When using self as you reared the following error is generated: Undefined class constant 'juiThemeSelectId'
i'm sorry, i didn't realized, that juiThemeSelectId isn't static in your example... see @Rizier123 answere

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.