PHP 5: const vs static
In the context of a class, static variables are on the class scope (not the object) scope, but unlike a const, their values can be changed.
class ClassName { static $my_var = 10; /* defaults to public unless otherwise specified */ const MY_CONST = 5;}echo ClassName::$my_var; // returns 10echo ClassName::MY_CONST; // returns 5ClassName::$my_var = 20; // now equals 20ClassName::MY_CONST = 20; // error! won't work.
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.
Edit: It is important to note that PHP 7.1.0 introduced support for specifying the visibility of class constants.
One last point that should be made is that a const is always static and public. This means that you can access the const from within the class like so:
class MyClass{ const MYCONST = true; public function test() { echo self::MYCONST; }}
From outside the class you would access it like this:
echo MyClass::MYCONST;
Constant is just a constant, i.e. you can't change its value after declaring.
Static variable is accessible without making an instance of a class and therefore shared between all the instances of a class.
Also, there can be a static local variable in a function that is declared only once (on the first execution of a function) and can store its value between function calls, example:
function foo(){ static $numOfCalls = 0; $numOfCalls++; print("this function has been executed " . $numOfCalls . " times");}