Oops / Encapsulation / What is Static function
Static Function
-
Note
1. What is static function
a static function is a class-level function. It belongs to the class, not to any single object.
the keyword "static " is used to declare a static function
No object needed to access it
Access with class name
2. Difference between static and non-static function
Features Static function Non static function Belongs To Class itself Each object (instance) Accessed With ClassName::method() $object->method() Access $this No Yes Access static vars Yes (self::$var) Yes Access instance vars No Yes ($this->var) Object creation needed No Yes Inheritance not polymorphic supports inheritance & overriding 3. When to Use Static function
It is used when the method does not access instance properties ($this->var) . Data is passed as function parameter
4. When not to use static function
It is not used when the method access instance properties ($this->var)
when you plan function overriding
Can we use static function instead of non-static function?
Technically yes, when If the Function Does Not Use Object Data.
Can we use non-static function instead of static function?
Technically yes, But It wastes memory. Each new object takes up extra memory
What is static class
Static class is a class which contains only static properties and static functions
MANVIA BLOG