I try to use a variable in each instance for a class.
My example class:
class test {
private static $gvalue;
function setValue($value)
{
$this->gvalue = $value;
}
function getValue()
{
return $this->gvalue;
}
}
Now I create to instances of this class "test" and print out some values.
$obj = new test();
$obj2 = new test();
echo "1: ";
echo $obj->getValue();
echo " / ";
echo $obj2->getValue();
$obj->setValue("green");
echo "<BR>2: ";
echo $obj->getValue();
echo "/";
echo $obj2->getValue();
My expectation was to get the following output:
1: / 2: green/green
But the result is:
1: / 2: green/
Did I understand something wrong? Or ist that not possible in PHP? Goal at the end. I would like to set some variables/arrays during the creation of an instance (__construc) and us that for every instance during the code (per user request).
You have to change how you access the static property in your method implementation:
<?php
class Test {
private static $gvalue;
function setValue($value) {
self::$gvalue = $value;
}
function getValue() {
return self::$gvalue;
}
}
$obj1 = new Test();
$obj2 = new Test();
echo sprintf("1: %s/%s
", $obj1->getValue(), $obj2->getValue());
$obj1->setValue("green");
echo sprintf("2: %s/%s
", $obj1->getValue(), $obj2->getValue());
The output of that is:
1: /
2: green/green
You only set $gvalue
for $obj
:
$obj->setValue("green");
When you echo $obj2->getValue();
the value of $gvalue
is still nothing, because you didn't set it for $obj2
.
$obj
and $obj2
are both different instances of the same class. They have the same characteristics etc. but they can hold different values. Thus the output that you got:
1: / 2: green/
is the correct output.