Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to solve error "using $this when not in object context"?

Tags:

oop

php

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?

like image 650
Christopher Avatar asked Aug 17 '15 15:08

Christopher


1 Answers

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->propertie.

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.

like image 142
Dmitrii Cheremisin Avatar answered Oct 02 '22 01:10

Dmitrii Cheremisin