php increment a number in static constructor -
i need increment number in constructor of class, without calling static functions. code follows:
class addup { static public $num; function __construct($num) { echo 'my number is==>' . $num; static::$num++; } } $inc = new addup();//instantiated object echo '<br>'; echo $inc::$num;//should 2, still 1, should $inc = new addup() or $inc->addup() implemented in class? echo '<br>'; echo $inc::$num;//should 3, still 1 echo '<br>'; echo $inc::$num;//should 4, still 1
any ideas welcome, thank you
upd made following refactoring:
$inc = new increment();//my number is==>2 echo '<br>'; $inc = new increment();//my number is==>3 echo '<br>'; $inc = new increment();//my number is==>4 echo '<br>'; $inc = new increment();//my number is==>5
is way without calls functions in class?
a static property means value of static property same across multiple instantiations of class.
this may demonstrate whats happening code better example
side note: parameter passing had no effect on , doing nothing
<?php class addup { static public $num; function __construct() { static::$num++; } } $inc1 = new addup(); // calls constructor therefore +1 echo php_eol; echo $inc1::$num; // 1 $inc2 = new addup(); // calls constructor therefore +1 echo php_eol; echo $inc2::$num; // 2 $inc3 = new addup(); // calls constructor therefore +1 echo php_eol; echo $inc3::$num; // 3 // if @ $inc1::$num; after instantiating inc2 , inc3 echo php_eol; echo $inc1::$num; // not 1 whatever last incremented i.e. 3
Comments
Post a Comment