April 22, 2025

Constant and Static:

A constant is a value that cannot be changed after it is declared.

A static variable is a variable that can be accessed without creating an instance of the class and is shared between all instances of the class. In addition, there can be a static local variable in a function that is declared only once, on the first execution of the function, and retains its value between function calls.

When used in the context of a class, static variables are on the class scope, not the object scope. Unlike a constant, the value of a static variable can be changed. However, public, protected, and private access modifiers apply to class variables, including static variables, but not to constants, which are always public.

A public static variable can be accessed anywhere via ClassName::$variable, while a protected static variable can be accessed by the defining class or extending classes via ClassName::$variable. A private static variable can only be accessed by the defining class via ClassName::$variable.

For example:

class ClassName {
    public static $my_var = 10; // Defaults to public unless otherwise specified
    const MY_CONST = 5;
}

echo ClassName::$my_var; // Returns 10
echo ClassName::MY_CONST; // Returns 5

ClassName::$my_var = 20; // Now equals 20
ClassName::MY_CONST = 20; // Error! Won't work.

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, for example:

function test() {    
static $testNumOfCalls = 0;    
$testNumOfCalls++;    
print("This function 'Test' has been executed " . $testNumOfCalls . " times"); 
}

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 TestClassName {     
static $mytestvar 	= 99;  			/* defaults to public unless otherwise specified */     
const MY_CONST 	= 33; 
} 	

echo ClassName::$mytestvar;   		// returns 99 	
echo ClassName::MY_CONST;  	        // returns 33 	
ClassName::$mytestvar 	= 100;          // now equals 100 	
ClassName::MY_CONST 	= 133;  	// 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 variables.

  1. public static variables can be accessed anywhere via ClassName::$variable.
  2. protected static variables can be accessed by the defining class or extending classes via ClassName::$variable.
  3. private static variables can be accessed only by the defining class via ClassName::$variable.

About The Author

Leave a Reply

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