Which is best $this or self or static when referencing const variable?

Viewed 2785

I learned that static is better than self because self does late static binding.

But I wonder which would be best at referencing const variable.

class Black
{
    const color = 'black';

    public function byThis()
    {
        return $this::color;
    }

    public function bySelf()
    {
        return self::color;
    }

    public function byStatic()
    {
        return static::color;
    }
}

I checked all of three getters work well. Which is the best choice? (I use PHP 7.0)

2 Answers

Keywords self and static are different in this way:

class White {
    const color = "white";

    public function byThis()
    {
        return $this::color;
    }

    public function bySelf()
    {
        return self::color;
    }

    public function byStatic()
    {
        return static::color;
    }
}

class Black extends White
{
    const color = "black";
}

$black = new Black;
echo "byThis: " . $black->byThis() . PHP_EOL;
echo "bySelf: " . $black->bySelf() . PHP_EOL;
echo "byStatic: " . $black->byStatic() . PHP_EOL;

Output:

byThis: black
bySelf: white
byStatic: black

I would expect output to be black with $black instance, so static is better in my opinion.

Related