Using static:: versus self:: in object oriented PHP

php static

Both “static” and “self” are keywords in PHP, but which one do you use and when? On my previous article about PSR-0 and PSR-4 autoloading I got a comment from Arnold that I should use “static” instead of “self”. Thank you again Arnold, you were completely right! I did not know this, so I decided to get to the bottom of it. There are several Stack Overflow answers on this subject, listed here in order of relevance:

  1. PHP Can static:: replace self::?
  2. What is the difference between self::$bar and static::$bar in PHP?
  3. New self vs. new static
  4. When to use self vs $this?

PHP example classes using “static”

After reading Stack Overflow, I wrote some code that covers everything discussed in the links above.

<?php
 
class Animal
{
    public static $name = "animal";
 
    // Return the class that is represented by "self::"
    public function getSelfClass()
    {
        return get_class();
    }
 
    // Return the class that is represented by "static::"
    public function getStaticClass()
    {
        return get_called_class();
    }
 
    public function selfVar()
    {
        return self::$name;
    }
 
    public function staticVar()
    {
        return static::$name;
    }
 
    public function selfMethod()
    {
        return self::getName();
    }
 
    public function staticMethod()
    {
        return static::getName();
    }
 
    protected function getName()
    {
        return "animal";
    }
 
}
 
class Penguin extends Animal
{
    public static $name = "penguin";
 
    protected function getName()
    {
        return "penguin";
    }
}
 
var_dump(Penguin::selfVar());
var_dump(Penguin::staticVar());
var_dump(Penguin::selfMethod());
var_dump(Penguin::staticMethod());
var_dump(Penguin::getSelfClass());
var_dump(Penguin::getStaticClass());

Output of the above script:

string(6) "animal"
string(7) "penguin"
string(6) "animal"
string(7) "penguin"
string(6) "Animal"
string(7) "Penguin"

Discussion on Reddit

There is an interesting discussion on Reddit about this post where people argue that static variables (and methods) should not be considered “object oriented”. Also people say that the use of the “static” keyword is bad practice. I tend to disagree, since there are some very common uses for “static” variables. For instance, the singleton pattern requires static variables to be applied.

Conclusion

As you can see, both on variables and methods, when you use “self::” you refer to the current class (like “get_class” does) and when you use “static::” you refer to the called class (like “get_called_class” does). I hope this post helps you to understand the difference between “static” and “self”.

Share