Reputation: 7638
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 !
Upvotes: 0
Views: 100
Reputation: 5605
static means : for all possible instances, the same variable will be used
function__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.
Upvotes: 0
Reputation: 88647
Static 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".
I think you are getting confused between static
and final
or const
.
Manual refs:
Upvotes: 0
Reputation: 191729
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).
Upvotes: 0
Reputation: 2777
function__construct()
{
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.
Upvotes: 1
Reputation: 70460
No, static means without instance, you are probable looking for constants.
Upvotes: 2