Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/forums/php/)
-   -   cant increment PHP class's static variable (http://www.go4expert.com/forums/increment-php-classs-static-variable-t26419/)

narekm 2Aug2011 01:05

cant increment PHP class's static variable
 
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 :pleased:

narekm 2Aug2011 01:09

Re: cant increment PHP class's static variable
 
Please just delete "echo"-s in front of change functions .. even in that case it didnt work

pein87 3Aug2011 15:46

Re: cant increment PHP class's static variable
 
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


All times are GMT +5.5. The time now is 14:21.