What is the difference between Static::Property, Classname::property, self::property?

Asked

Viewed 146 times

2

I know that the parent::propriedade, you select parent property, but I’m not able to differentiate these other three when I use within the scope of the class. Both work, but what’s the difference?

1 answer

2


We are always talking about static properties there.

The self::propriedade is the way to refer to a static property within the class code. It’s like using the this, but it’s for static members, not just properties. You can use the class name as well.

Already nomeClasse::propriedade is the use of the same thing, but is used outside the class code, ie when consuming the class.

And static::propriedade It’s like I’m the self but for constants and if there is inheritance in this class it will take the static property of the derived class and not the base class, if there is a static property with the same name in the derivative.

class A {
    const X = 'A';
    public function x() {
        echo static::X;
    }
}

class B {
    public static $X = 'B';
    public function x() {
        echo self::$X;
    }
    public function x2() {
        echo B::$X;
    }
}

class C extends A {
    const X = 'C';
}

$c = new C();
$c->x();
echo C::X;
echo c::X;
$b = new B();
$b->x();
$b->x2();
echo b::$X;
echo B::$X;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks @Maniero!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.