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 ToClass itselfEach object (instance)
    Accessed WithClassName::method() $object->method()
    Access $thisNo Yes
    Access static varsYes (self::$var) Yes
    Access instance varsNo Yes ($this->var)
    Object creation neededNo Yes
    Inheritancenot 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