php-引用const变量时哪个最好$this或self或static?
作者:互联网
我了解到静态优于自我,因为自我进行了后期的静态绑定.
但是我想知道哪种方法最适合引用const变量.
class Black
{
const color = 'black';
public function byThis()
{
return $this::color;
}
public function bySelf()
{
return self::color;
}
public function byStatic()
{
return static::color;
}
}
我检查了所有三个吸气剂是否工作良好.哪个是最佳选择? (我使用PHP 7.0)
解决方法:
PHP class constants documentation建议对类中的常量使用self ::.我个人会留下来.
每个关键字都返回相同的值,即使该类用另一个常量值扩展了另一个类,除了parent ::也返回了父类的值:
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;
输出为:
byThis: black
bySelf: black
byStatic: black
byParent: white
标签:self,const,static,this,php 来源: https://codeday.me/bug/20191111/2017480.html