Skip to content

Instantly share code, notes, and snippets.

@Scemist
Last active November 17, 2022 12:43
Show Gist options
  • Save Scemist/07a429363a93fe62ee6639ebed9f18cb to your computer and use it in GitHub Desktop.
Save Scemist/07a429363a93fe62ee6639ebed9f18cb to your computer and use it in GitHub Desktop.
PHP Inherance Keywords: self, static, $this, ClassName
  • self
  • static
  • $this
  • ClassName

Difference Self and Parent

Child has foo() Parent has foo()
self::foo() YES YES Child foo() is executed
parent::foo() YES YES Parent foo() is executed
self::foo() YES NO Child foo() is executed
parent::foo() YES NO ERROR
self::foo() NO YES Parent foo() is executed
parent::foo() NO YES Parent foo() is executed

If both havent the method, error will be returned

$this and self

  • $this->member for non static methods
  • self::member for static methods

self and static

<?php

class Pai
{
    public static function quemSou()
    {
        echo __CLASS__;
    }

    public static function chamaComSelf()
    {
        self::quemSou(); // Onde foi declarada
    }
    
    public static function chamaComStatic()
    {
        static::quemSou(); // Onde foi chamada
    }
}

class Filho extends Pai
{
    public static function quemSou()
    {
        echo __CLASS__;
    }
}

Filho::chamaComSelf(); // Sou o Pai
Filho::chamaComStatic(); // Sou o Filho
  • self chamará o método de onde foi declarado, static chamará o método de onde foi chamado

self, parent and static

<?php

class Vo
{
    public static function quemSou()
    {
        echo __CLASS__;
    }
}

class Pai extends Vo
{
    public static function quemSou()
    {
        echo __CLASS__;
    }

    public static function teste()
    {
        self::quemSou();
        parent::quemSou();
        static::quemSou();

        echo PHP_EOL;
    }
}

class Filho extends Pai
{
    public static function quemSou()
    {
        echo __CLASS__;
    }
}

Filho::teste(); // Pai - Vo - Filho
Pai::teste();   // Pai - Vo - Pai

// self   - método de onde foi declarado
// parent - método de onde foi declarado
// static - método de onde foi chamado

self and ClassName

ClassName does not preverse initial class that was called in inherance context

<?php

class Vo
{
    static function foo()
    {
        echo get_called_class();
    }
}

class Pai extends Vo
{
    static function quemSouComSelf()
    {
        self::foo();
    }
    static function quemSouComNomeDaClasse()
    {
        Pai::foo();
    }
}

class Filho extends Pai
{
}

Filho::quemSouComSelf();         // Filho
Filho::quemSouComNomeDaClasse(); // Pai

Sources

https://www.php.net/manual/en/language.oop5.late-static-bindings.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment