/ php

PHP - static vs self

PHP's difference between static and self.


class Mom
{
    private const DEFAULT_AGE = 21;


    public static function getName(): string
    {
        return 'Alice';
    }
    
    public function tellAge(int $age = self::DEFAULT_AGE): string
    {
        return 'My age is: ' . $age;
    }
    
    public function tellAge2(int $age = self::DEFAULT_AGE): string
    {
        return 'My age is: ' . $age;
    }
    
    public static function tellAge3(): string
    {
        return 'My default age is: ' . self::DEFAULT_AGE;
    }
    
    // this would explode with 'Fatal error: "static::" is not allowed in compile-time constants'
    //public function tellAge4(int $age = static::DEFAULT_AGE): string
    //{
    //    return 'My age is: ' . $age;
    //}
    
    public static function returnInstance(): self
    {
        return new self();
    }
    
    public static function returnInstance2(): self
    {
        return new static();
    }
}

class Child extends Mom
{
    private const DEFAULT_AGE = 1;

    public static function getName(): string
    {
        return 'Bob';
    }
    
    // tell age 1 is not overridden
    
    public function tellAge2(int $age = self::DEFAULT_AGE): string
    {
        return 'My age is: ' . $age;
    }
    
    public static function tellAge3(): string
    {
        return 'My default age is: ' . self::DEFAULT_AGE;
    }
}


$alice = new Mom();
$bob = new Child();

echo '---------------'. PHP_EOL;
echo Mom::getName() . PHP_EOL;
echo Child::getName() . PHP_EOL;

echo '---------------'. PHP_EOL;
echo $alice->tellAge() . PHP_EOL;
echo $bob->tellAge() . PHP_EOL;

echo '---------------'. PHP_EOL;
echo $alice->tellAge2() . PHP_EOL;
echo $bob->tellAge2() . PHP_EOL;

echo '---------------'. PHP_EOL;
echo Mom::tellAge3() . PHP_EOL;
echo Child::tellAge3() . PHP_EOL;

echo '---------------'. PHP_EOL;
echo get_class(Mom::returnInstance()) . PHP_EOL;
echo get_class(Child::returnInstance()) . PHP_EOL;

echo '---------------'. PHP_EOL;
echo get_class(Mom::returnInstance2()) . PHP_EOL;
echo get_class(Child::returnInstance2()) . PHP_EOL;

Output:

---------------
Alice
Bob
---------------
My age is: 21
My age is: 21
---------------
My age is: 21
My age is: 1
---------------
My default age is: 21
My default age is: 1
---------------
Mom
Mom
---------------
Mom
Child

Tags:
#php #static #self

TvK

IT and languages. Feel free to be a grammar-nazi and correct my English (or any other language).

Read More