cant increment PHP class's static variable

narekm's Avatar
Go4Expert Member
Hello there. Here is my php code
PHP Code:
class car{
static 
$one=1;

static function 
change()
{
 
self::$one=self::$one++;

}

}
car::$one=2;
echo 
car::$one."<br />";
echo 
car::change();
echo 
car::$one."<br />";
echo 
car::change();
echo 
car::$one."<br />";
echo 
car::change();
echo 
car::$one."<br />"
I expected it to increment the variable but it echoed 2 2 2 2 instead of expected 2 3 4 5

Thank you for your attention!!!

Will be waiting
narekm's Avatar
Go4Expert Member
Please just delete "echo"-s in front of change functions .. even in that case it didnt work
pein87's Avatar
Ambitious contributor
try

PHP Code:
class car

static 
$one=1

static function 
change() 

 return 
self::$one++; 



}

$i;
for (
$i 1$i 11$i++)
{
echo 
car::change();

the for loop just makes it print out a certain number of times, while the change function changes the value on each call.

if you use the below script it will show the value as 10
PHP Code:
<?php

class car

static 
$one=1

static function 
change() 

 return 
self::$one++; 



}

car::change();
car::change();
car::change();
car::change();
car::change();
car::change();
car::change();
car::change();
car::change();
echo 
car::$one;

?>
Hope this works, I did test the code and it worked on my machine using php 5.2.11. and 5.3.5

Last edited by pein87; 3Aug2011 at 15:51..