Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use static variables/functions in php?

Tags:

oop

php

static

People also ask

When should I use static methods in PHP?

When to define static methods ? The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method.

When should I use static variables?

use static variables when : The value of the variable is independent of the objects (not unique for each object). E.g. number of students. Voting is disabled while the site is in read-only mode. Voting is disabled while the site is in read-only mode.

Should I use static function PHP?

You should not use static method (in OOP). If you need a static method in one of your class, this means you can create a new singleton/service containing this method and inject it to the instance of classes needing it.

Why do we need static functions?

Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.


You use static when you want to use a method / variable that is not tied to an instance. That can happen when :

  • There is no relation with your purpose and an instance (useful for toolboxes in languages that doesn't allow anything else that OOP like Java, but not useful in PHP).

  • You want to control the access to the instance. Most often, the instance you want to deal with is not defined when you write the code, but will be at execution. The Singleton pattern is the best example. You can use static methods as factories to create an object according to the context or sharing resources with other instances. E.G : a static member can give access to a data base layer so part of the app accesses the same one from anywhere and it's opened/closed without conflicts.

  • Performances matter and the method will be executed a lot of times. In that case, you will save some CPU time preventing the interpreter from looking up the member to an instance at each call. But still, if perfs becomes such an issues that you come to this solution, it might time to reconsider your architecture, or the use of a binding to a faster language for the critical parts of the code.

  • You have a method that is related to a type but will be applied to another. It can make sense to write the method into the declaration of the first type, but set it static since it expects an instance of the another one.

The perfect example is a String parser :

class MyObject 
{
 static function parse($str)
 {
    $obj = new MyObject();
    // some parsing/setting happens here
    return $obj;
 }
}

// you create an object "MyObject" from a string, so it's more obvious
// to read it this way :
$new_obj = MyObject::parse("This a description of a super cool object");

Static functions and variable are used to access Variables/functions in a global scope, like this:

echo myClass::myVariable;
echo myClass::myFunction();

When something is static, it can be accessed anywhere, and is very similar to a procedural type function, except it can use self and is contained in the classes scope.

class myClass{
    static $myVariable = "myVar";
    static function myFunction()
    {
       return "myFunc";
    }
}

One of the ways to use this is to keep only one instance of a class, or a Singleton Method.

class myClass
   {
    static $class = false;
    static function get_connection()
    {
        if(self::$class == false)
        {
            self::$class = new myClass;
        }
        else
        {
            return self::$class;
        }
    }
    private function __construct()
    {
         // my constructor
    }
    // Then create regular class functions.
   }

Because it has a private constructor, it cannot be instantiated with the new operator, so you are forced to call myClass::get_connection() to get a class. That function can make the new class (because it is a member of the class). Then it stores the class in a static variable, and if you call the function again, it will simply returned the created class.

In the end, the static keyword is used to keep things, well, static, in reference to scope. It means you don't want anything 'changing' because of the current scope. While the Singleton method stretches this a little, it keeps with the same idea that you always have the 'same' class, not matter what scope you are in.

PHP Documentation
Static Keyword
Scope Resolution Operator

StackOverflow Knowledge
How to Avoid Using PHP Global Objects
Share Variables Between Functions in PHP Without Using Globals
Making a Global Variable Accessible For Every Function inside a Class
Global or Singleton for Database Connection
PHP Classes: when to use :: vs. -> ?


Also it is very usefull for caching if a method will be called very often and do just the same thing, for example:

/**
 * Returns true if the user is logged in through shibboleth
 *
 * @return boolean true on success, else false
 */
protected function is_logged_in() {

    //Check shibboleth headers
    if (!empty($_SERVER['HTTP_SHIB_IDENTITY_PROVIDER']) || !empty($_SERVER['Shib-Identity-Provider'])) {
        if (!empty($_SERVER[$this->core->dbconfig("shib_auth", self::SHIB_AUTH_CONFIG_UID)])) {
            return true;
        }
    }
    return false;
}

This method will be called within my framework very often and there it will do for every call a database lookup for my configuration $_SERVER key

So while the page is processed i call maybe 10 times in one page load it will have 10 database calls but i changed it to:

/**
 * Returns true if the user is logged in through shibboleth
 *
 * @return boolean true on success, else false
 */
protected function is_logged_in() {
    static $logged_in = null;
    if($logged_in != null) {
        return $logged_in;
    }

    //Check shibboleth headers
    if (!empty($_SERVER['HTTP_SHIB_IDENTITY_PROVIDER']) || !empty($_SERVER['Shib-Identity-Provider'])) {
        if (!empty($_SERVER[$this->core->dbconfig("shib_auth", self::SHIB_AUTH_CONFIG_UID)])) {
            $logged_in = true;
            return true;
        }
    }
    $logged_in = false;
    return false;
}

So it just check for every page load one time the normal behaviour if i logged in and cache the result. next time it will just return the cached value. This feature i use very often to have more performance.

Hope this helps.


Here's a random, though fairly good description of the differences between static and instance methods.

From the post:

Instance methods are instance methods because they rely on the state of the specific object instance. Instance methods are tied to a particular instance because the behavior that the method invokes relies upon the state of that particular instance.

When you declare a method as static, you define that method as being a class method. A class method applies to the class as opposed to any particular instance. The behavior instigated by a class method does not rely on the state of a particular instance. In fact, a static method cannot rely on an instance's state since static methods lack access to this reference. Instead, the behavior of a class method either depends on a state that all objects share at the class level, or is independent of any state at all.

If a method relies on an object instance's state it should be an instance methods. If a method is general for all or no instances of a class, and does not rely on the object state, it should be a static method. Instance methods are most commonly used. However static methods are very useful for utility and factory classes amogst many other uses.


Generally using static function you can optimize the speed as well as memory and the scope of method should not be changed its should be static in nature and you can access the objects static properties ,methods without initiating them so saves the memory in mean time.


Static elements have a number of characteristics that can be useful.

  1. First, they are available from anywhere in your script (assuming that you have access to the class). This means you can access functionality without needing to pass an instance of the class from object to object or, worse, storing an instance in a global variable.

  2. Second, a static property is available to every instance of a class, so you can set values that you want to be available to all members of a type.

  3. Finally, the fact that you don’t need an instance to access a static property or method can save you from instantiating an object purely to get at a simple function.