7

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)

Luan
  • 95
  • 1
  • 6
  • Possible duplicate of [When to use self over $this?](https://stackoverflow.com/questions/151969/when-to-use-self-over-this) – Fred Gandt Aug 01 '17 at 03:29
  • 1
    They're not the same if you create a subclass that redefines the constant. `byThis()` and `byStatic()` will return the subclass's value. – Barmar Aug 01 '17 at 03:29

2 Answers2

6

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.

RaDim
  • 630
  • 6
  • 6
3

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
Dan
  • 5,140
  • 2
  • 15
  • 30
  • 4
    Yes, but no - http://sandbox.onlinephpfunctions.com/code/9c3b8895568b596ded6e0c10fcb4efa658221cd0 If the methods are in the parent class, things are very different – Martin Dimitrov Nov 13 '20 at 10:36