7

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.

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

I knew it was going to be something simple. Haven't done much OOP in PHP, but thanks for the quick response!
You can define the default value for a property, see stackoverflow.com/a/8779542/367456
3

As long as the default value is a constant (expression), you can just note that down in the definition of the property:

class Tester
{
    const DEFAULT_VAL = 500;

    private $val = self::DEFAULT_VAL;

    public function __construct() {
    }
}

That done it's already set when the object get's constructed, so you don't have to write code to set it. Demo.

2 Comments

Good to know, appreciate the response. However I am doing this in the constructor because I intend to allow this value to be explicitly set in the constructor, otherwise use the default value.
Which would be why you predefine it above the constructor. You can still change it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.