Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 473
Luan Avatar asked Aug 01 '17 03:08

Luan


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.

like image 81
RaDim Avatar answered Sep 18 '22 15:09

RaDim


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
like image 20
Dan Avatar answered Sep 19 '22 15:09

Dan