Mark Kaplun
Mark Kaplun

Reputation: 285

Is there any reason to use self:: over static:: when calling static method inside a PHP class

static:: provides late binding which is a must if the static functions of the class can be overriden by an extending class and the static method is called from within the class. But in the case that a class can not be extended (it is final for example) would it be wrong to use static:: then as well?

Another way to ask the same, what should be the rule of thumb when calling static methods, to use static:: or self::, or is there such a big drawback for using static:: that you should use it only when strickly required?

Upvotes: 2

Views: 172

Answers (1)

Dharman
Dharman

Reputation: 33238

There's no difference between them in a final class, so use whichever you want.

Both calls will return A.

<?php

class Dad {
    static function getStatic() {
        return new static;
    }
    
    static function getSelf() {
        return new self;
    }
}

trait Useless {
    static function getStatic() {
        return new static;
    }
}

final class A extends Dad {
    use Useless;
    
    static function getSelf() {
        return new self;
    }
}

var_dump(A::getStatic()::class);
var_dump(A::getSelf()::class);

Example

Upvotes: 1

Related Questions