Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constant vs properties in php?

Tags:

php

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?

like image 217
Adam Ramadhan Avatar asked Dec 22 '22 23:12

Adam Ramadhan


2 Answers

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.

like image 158
NikiC Avatar answered Jan 07 '23 04:01

NikiC


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

like image 20
Hamid Nazari Avatar answered Jan 07 '23 02:01

Hamid Nazari