Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Assigning class constant value to property in constructor

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.

like image 918
djentastic Avatar asked Jan 08 '12 17:01

djentastic


1 Answers

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
like image 123
Paul Avatar answered Nov 14 '22 23:11

Paul