What is difference between constant and static in php

Constants

Besides properties and methods in the body of the class can also be defined constants.
A constant is declared with the const keyword followed by a name (is not prefixed with a dollar sign like properties).
– Syntax:
const CONSTANT_NAME
The main difference between properties and constants is that the constant value cannot be changed once it is set.
Constants are recognized as public, they are not defined with public, private or protected attribute.
Constants are accessed via the class name in conjunction with ::
– Syntax:
Class_Name::CONSTANT_NAME

 

I also assume, since static members (functions and variables) do not get instantiated into a new corresponding object, then constants also do not (since they are accessed with the :: operator).

class ClassName {
static $my_var = 20; /* defaults to public unless otherwise specified */
const MY_CONST = 10;
}
echo ClassName::$my_var; // returns 20
echo ClassName::MY_CONST; // returns 10
ClassName::$my_var = 50; // now equals 50
ClassName::MY_CONST = 100; // error! won’t work.

¬†class constants are always public but static variables can be private or protected. I use class constants mostly for ‘enumerated’ parameter values.

Public, protected, and private are irrelevant in terms of consts (which are always public); they are only useful for class variables, including static variable.

  • public static variables can be accessed anywhere via ClassName::$variable.
  • protected static variables can be accessed by the defining class or extending classes via ClassName::$variable.
  • private static variables can be accessed only by the defining class via ClassName::$variable.
  • Declaring a class method or property as statis makes them accessible without needing an instantiation of the class.A class constant is just like a normal constant, it cannot be changed at runtime. This is also the only reason you will ever use const for.Private, public and protected are access modifiers that describes who can access which parameter/method.Public means that all other objects gets access. Private means that only the instantiated class gets access. Protected that the instantiated class and derived classes gets access