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

2

8

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)

Xiphoid answered 1/8, 2017 at 3:23 Comment(2)
Possible duplicate of When to use self over $this?Oberhausen
They're not the same if you create a subclass that redefines the constant. byThis() and byStatic() will return the subclass's value.Handoff
C
7

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.

Capture answered 4/7, 2018 at 17:22 Comment(0)
P
2

The PHP class constants documentation recommends the use of self:: for a constant within a class. I personally would stay with this.

Every one of the keywords return the same value, even if the class extends another class with another value for the constant, except for parent:: which returns the value of the parent class:

class White {
    const color = "white";
}

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

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

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

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

    public function byParent() {
        return parent::color;
    }
}

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

The output would be:

byThis: black
bySelf: black
byStatic: black
byParent: white
Pericles answered 1/8, 2017 at 3:45 Comment(1)
Yes, but no - sandbox.onlinephpfunctions.com/code/… If the methods are in the parent class, things are very differentGroot

© 2022 - 2024 — McMap. All rights reserved.