7

I've this trait class:

trait Example
{
    protected $var;

    private static function printSomething()
    {
        print $var;
    }

    private static function doSomething()
    {
        // do something with $var
    }
}

And this class:

class NormalClass
{
    use Example;

    public function otherFunction()
    {
        $this->setVar($string);
    }

    public function setVar($string)
    {
        $this->var = $string;
    }
}

But i'm getting this error: Fatal error: Using $this when not in object context.

How can i solve this issue? I can't use properties on a trait class? Or this isn't really a good practice?

Christopher
  • 3,379
  • 7
  • 25
  • 36
  • 2
    where/how are you calling setvar()? to get that error you'd have to be doing something like `$foo = NormalClass::setVar()` or whatever. and for your printSomething, `$var` would be an undefined local variable. – Marc B Aug 17 '15 at 15:03
  • @MarcB i've updated my question. – Christopher Aug 17 '15 at 15:05
  • 3
    that doesn't help, now it becomes "how/where are you calling otherFunction()"? You need to show the ENTIRE call chain. – Marc B Aug 17 '15 at 15:05
  • You probably mean `print static::$var;`, since that method is *static*. Instance variables aren't going to help you there. – bishop Aug 17 '15 at 15:06
  • 5
    you are mixing instance-variables (which are part of the instance of a class) with class-variables (static, which are part of the class itself), `$this->var VS. self::$var` – birdspider Aug 17 '15 at 15:06

2 Answers2

20

Your problem is connected with differences between class's methods/properties and object's.

  1. If you define a property as static - you should access it through your class like classname/self/parent ::$property.
  2. If not static - then inside static property like $this->property.

For example:

trait Example   
{
    protected static $var;
    protected $var2;
    private static function printSomething()
    {
        print self::$var;
    }
    private function doSomething()
    {
        print $this->var2;
    }
}
class NormalClass
{
    use Example;
    public function otherFunction()
    {
        self::printSomething();
        $this->doSomething();
    }
    public function setVar($string, $string2)
    {
        self::$var = $string;
        $this->var2 = $string2;
    }
}
$obj = new NormalClass();
$obj -> setVar('first', 'second');
$obj -> otherFunction();

Static function printSomething can't access not static propertie $var! You should define them both not static, or both static.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Dmitrii Cheremisin
  • 1,498
  • 10
  • 11
0

Using $this when not in object context because of this code

$this->form_validation->set_rules('username','Username','required');
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Hannah
  • 1