rsk82
rsk82

Reputation: 29397

please explain to me nature of this error showing up when setting static variable

What I wanted to do is to set static $variable to 'new value'. This is my code:

class myobj {

    static protected $variable = null;

    static function test() {
        static::variable = 'new value'
    }
}

$obj = new myobj();
$obj->test();

But an error shows up:

Parse error: syntax error, unexpected '=' in D:\!TC\www\error.php on line 8

Upvotes: 0

Views: 49

Answers (3)

djhaskin987
djhaskin987

Reputation: 10077

you need to use self:

class myobj {
  static protected $variable = null;
  static function test() {
    self::$variable = 'new value';
  }
}

Upvotes: 1

nickb
nickb

Reputation: 59709

You're missing the dollar sign and a colon, and should use self to reference the data member $variable:

self::$variable = 'new value';

Upvotes: 1

Maxime Pacary
Maxime Pacary

Reputation: 23061

Use:

self::$variable = 'new value';

instead of:

static::variable = 'new value'

BTW I strongly encourage you to use an IDE able to directly tell you basic syntax errors, like Aptana Studio or PHPStorm.

Upvotes: 2

Related Questions