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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With