A class is a user-defined data type that holds its own data members and member functions that can be accessed and used by creating one or more instances of that class. Every time a class is instantiated, the values that it holds are different and unique to the particular instance or object and not to that class. Static Classes brings forth a property wherein a class itself holds values that remain the same and aren’t unique. Another property of Static Classes is that we can do the aforementioned without having to create an instance of the class.
How to create a static class?
It’s fairly simple. The variables and methods that are declared and defined within a class are to be declared as static with the use of static keyword, so that they can be used without instantiating the class first.
An important point to note here is that, since this means a class variable can be accessed without a specific instance, it also means that there will only be one version of this variable. Another consequence is that a static method cannot access non-static variables and methods since these require an instance of the class.
To access the static class and it’s method use the following synatx:
Example 1: The following code returns the current date without instantiating the class Date. In this case, the format of the date and not the actual date remains the same.
Output: April 30th, 2020 2020/04/30 10:48:36
Example 2: The following code checks whether the string is valid or not. It is valid if it’s length is equal to 13.
String is valid! String is NOT valid!
- When to use static vs instantiated classes in PHP?
- Understanding storage of static methods and static variables in Java
- Understanding "static" in "public static void main" in Java
- Difference between static and non-static variables in Java
- Difference between static and non-static method in Java
- New self vs. new static in PHP
- Difference between self::$bar and static::$bar in PHP
- Static Function in PHP
- Ruby Static Members
- What is Late Static Bindings in PHP ?
- Static vs Dynamic Website
- Comparison between static and instance method in PHP
- Types of Static Analysis Methods
- How to Serve Static Content using Node.js ?
- Difference between Static and Shared libraries
- “static const” vs “#define” vs “enum”
- PHP | Classes
- Classes of JSP API
- ES6 | Classes
- Why does PHP 5.2+ disallow abstract static class methods ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.