Tutorial

PHP const Keyword Explained

With PHP we can define such variables whose values can not be changed after assigning. These varibles called [code]CONSTANTS[/code].

What is const?

Constants are one type of variable which we can define for any class with keyword [code]const[/code]. Value of these variables can not be changed any how after assigning.

Class constants are diffrent than normal variables, as we do not need $ to declare the class constants. Values for the class constants can not be mathematical operation, function call, variable or property. It can have constant expression.

We can use these constants in interface also. If you are not sure what is Interface then you can refer this article for Interface in PHP.

If we are inside the class then values of the constants can be get using [code]self[/code] keyword, but accessing the value outside the class you have to use Scope Resolution Operator [code]::[/code].

If you access constant using class object and Arrow Operator [code]->[/code], you will end up with Notice of Undefined Property.

Example

[cc lang=”php”]

class example_class
{
const first_constant = “value of Constant”;
const second_constant = 345;

function display_constants()
{
// Inside Class self is used
echo self::first_constant . “\n”;
echo self::second_constant . “\n”;
}
}

// :: used to refer the Class Constants
echo example_class::first_constant . “\n”;

$class = new example_class();

// Will print two Constants
$class->display_constants();

// Shows Notice of Undefined Property
echo $class->first_constant;

[/cc]

Conclusion

It will be better to use these Class Constants when you have variables with the fixed value, so It can not be changed further. Your suggestions?

Shares:
  • saujiro
    December 29, 2011 at 2:31 pm

    Thank you sir for your tut, and I am very interested with frame for your example code. May I know what kind of plugin or script you used or maybe some tut for that…

    Reply
  • Faifas
    December 29, 2011 at 5:33 pm

    should be const FIRST_CONST;

    Reply
    • Avinash
      December 29, 2011 at 10:53 pm

      Why? If you think that Constant name must in CAPITAL form then its not true.

      Reply
      • David
        September 13, 2012 at 11:53 pm

        The reason Faifas mentioned it is because it’s been a, many decades long, common practice for constants (and manifest constants) to be in all capital letters. I believe this was started in the original C and has carried through in all languages which use a variant of C style syntax (which PHP is one).

        Reply
  • itoctopus
    December 29, 2011 at 6:38 pm

    It would have been nice if you displayed what will happen (the error that you will receive) if you try to assign a value to a constant after it’s already assigned.

    For example, what will happen if you try:

    $class->first_constant = “test”;

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *