user558134
user558134

Reputation: 1129

Php class and static properties inside constructor

Is it possible to change the default value of a static class property inside the constructor in php?

class Test { 
  public static $property = 'default';

  public function __construct() {
    self::$property = 'new value';
  }       
}

The code above doesn't do that. Thanks in advance!

EDITS

I know I can change the value outside the class

Test::$property = 'new value';
echo Test::$property;

I was wondering if I could do it inside class constructor.

Upvotes: 2

Views: 2127

Answers (3)

TeChn4K
TeChn4K

Reputation: 2405

With PHP 5.3, you can use the late static binding.

Replace "self" by "static" in your code :

class Test { 
  public static $property = 'default';

  public function __construct() {
    static::$property = 'new value';
  }       
}

It will works ;)

Upvotes: 2

M I
M I

Reputation: 3682

This is working for me.

class Test { 
  public static $property = 'default';
  public function __construct() {
     echo self::$property = 'new value'; // for EXample echo val of property
  }       
}
//When create a new object of class it shows / Assigns value of static property

$test = new Test();
echo Test::$property;

Upvotes: 0

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

You forgot a double point:

self::$property = 'new value';

Upvotes: 0

Related Questions