I have been trying to create a simple class, which defines default property values as class constants at the top of the class definition.
However, my code does not seem to be assigning the value of the constant to the property in the constructor.
class Tester {
const DEFAULT_VAL = 500;
private $val;
public function __construct() {
$val = self::DEFAULT_VAL;
}
public function show_val() {
echo "DEFAULT_VAL is " . self::DEFAULT_VAL . "<br />";
echo "val is " . $val;
}
}
$obj = new Tester();
$obj->show_val();
Running the code above yields the result:
const is 500
val is
I cannot figure out why I cannot assign the predefined, constant default value to the property from within the constructor.
You need to use $this->val
in place of $val
in two places in your code, since each instance of Tester has it's own val:
class Tester {
const DEFAULT_VAL = 500;
private $val;
public function __construct() {
$this->val = self::DEFAULT_VAL;
}
public function show_val() {
echo "DEFAULT_VAL is " . self::DEFAULT_VAL . "<br />";
echo "val is " . $this->val;
}
}
$obj = new Tester();
$obj->show_val();
Outputs:
DEFAULT_VAL is 500
val is 500
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With