PHP Static
In PHP language, the static keyword is mainly used for memory management. The static variable is shared by all the objects of that class. It is visible only within the class, but its lifetime is the entire program.
The static keyword can be used:
- Static Variable
- Static Method
Static Variable
To declare a variable as static is called as static variable.
Syntax:
static variable_name;
Example:
<?php class StaticVariable { public static $a = 5; public static function main() { echo "Area of the square: " . (self::$a * self::$a) . "\n"; } } // Call the main method StaticVariable::main(); ?>
Static Method
Method of a class can also be declared as static. But the static method can access only static data member.
Syntax:
static method_name() { ... }
Example:
<?php class StaticMethod { public static $a = 6; public static function square() { self::$a = 5; } public static function main() { self::square(); // Calling the static method echo "Area of the square: " . (self::$a * self::$a) . "\n"; } } // Call the main method StaticMethod::main(); ?>
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.