PHP - POO Difference between calls using literals or references

0

In PHP we can have a class like the following:

class Test {

    public static function xxx() {
        //hacer algo
    }

    public static function yyy() {
        //hacer algo
    }

    public static function zzz() {
        //hacer algo
    }


    public static function mi_test() {

        //Llamada literal al método de la propia clase
        Test::xxx();

        //Llamadas usando referencias
        self::yyy();
        self::zzz();
    }

} //class

Calling methods one way or another seems to work the same, are there differences?

I have observed, for example, that with the literal calls it is easier to locate errors, due to erroneous calls, in case of restructuring / refactoring the classes and moving methods, although I did not find preferences for one or the other in lists of good practices, then is it recommended one way over the other, in what cases and why?

    
asked by Orici 14.06.2017 в 00:13
source

1 answer

0

There is a small difference: self:: forwards static calls, while className:: does not. This is only important for the static links at run time in PHP 5.3 +.

In static calls, PHP 5.3+ remembers the class initially called. Using className:: causes PHP to "forget" this value (that is, it resets it to className), while self:: preserves it.

This can be understood by considering the following code:

VIEW DEMO

<?php 

class A 
{
    static function foo() 
    {
        echo get_called_class()."\n";
    }
}

class B extends A 
{
    static function bar() 
    {
        self::foo();
    }
    static function baz() 
    {
        B::foo();
    }
}

class C extends B 
{
}

C::bar(); //C
C::baz(); //B    
?>

Result

C
B

See this answer in SO in English.

    
answered by 14.06.2017 в 01:12