tags:

views:

96

answers:

3

I just don't get it,

class MyClass
{
    const constant = 'constant value';

    function showConstant() {
        echo  self::constant . "\n";
    }
}

class MyClass
{
    public $constant = 'constant value';

    function showConstant() {
        echo  $this->constant . "\n";
    }
}

Whats the main difference? Its just same as defining vars, isn't it?

Thanks

Adam Ramadhan

+2  A: 

By defining a const value inside a class, you make sure it won't be changed intentionally or unintentionally.

Hamid Nazari
A: 

Well, if I do $myClass->constant = "some other value" (given $myClass is an instance of MyClass) in the latter example, then the value is no longer constant. There you have the difference. The value of a constant can not be changed, because... it is constant.

Hanse
and the diffrence with static $var ?
Adam Ramadhan
this confuses the OP more than it answers the question. this is illegal in php: `$myClass->constant = "some other value"`
stillstanding
Nope, that is fully legal. Everyone ought to understand that $myClass is an instance of MyClass.
Hanse
@Adam: You can change the value of a static class variable: `MyClass::$variable = "some new value";` You can't change the value of a constant.
Bill Karwin
+4  A: 

Constants are constant (wow, who would have thought of this?) They do not require a class instance. Thus, you can write MyClass::CONSTANT, e.g. PDO::FETCH_ASSOC. A property on the other hand needs a class, so you would need to write $obj = new MyClass; $obj->constant.

Furthermore there are static properties, they don't need an instance either (MyClass::$constant). Here again the difference is, that MyClass::$constant may be changed, but MyClass::CONSTANT may not.)

So, use a constant whenever you have a scalar, non-expression value, that won't be changed. It is faster than a property, it doesn't pollute the property namespace and it is more understandable to anyone who reads your code.

nikic
solve, perfect.
Adam Ramadhan