self
static
$this
ClassName
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->member
for non static methodsself::member
for static methods
<?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
<?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
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
https://www.php.net/manual/en/language.oop5.late-static-bindings.php