class StaticTester
{
private static $id=0;
function__construct()
{
self::$id+=1;
}
public static function checkIdFromStaticMethod()
{
echo "Current Id from Static method is ".self::$id;
}
}
$st1=new StaticTester();
StaticTester::checkIdFromStaticMethod(); // this outputs 1.
Okay ,I am not getting why the output is 1? After all Static means the value cannot be changed !
No, static means without instance, you are probable looking for constants.
ReplyDeletefunction__construct()
ReplyDelete{
self::id+=1;
}
should be
function__construct()
{
self::$id+=1;
}
missed a dollar sign there :)
oops.... misread the question. i thought you had an error in your code hehe. which you did, but probably just a copy/paste error.
it becomes one since it's incremented by one each time a new object is created. and all the objects share the same id variable. this is what static means.
a number that can never change is called a constant, and declared with the keyword const in php.
static does not mean the value cannot be changed at all! You want const, or final (which PHP does not have). static will actually retain the value between method calls (since it's a member, it would anyway).
ReplyDeleteStatic does not mean that the value cannot be changed, it means that the value is held at the class level and not at the instance level. Other languages (such as Java) sometimes refer to this as a "class variable".
ReplyDeleteI think you are getting confused between static and final or const.
Manual refs:
static keyword
final keyword
Class constants
static means : for all possible instances, the same variable will be used
ReplyDeletefunction__construct()
{
self::$id+=1;
}
$st1=new StaticTester();
when doing the new , __construct is called , so your $id static variable will be used & increased.
may you do $st2=new StaticTester() , StaticTester::checkIdFromStaticMethod() will return 2 !!!
That's what your code is meant to do as it is written.
Agree with "constant" answers.