dousendun8411 2017-08-01 03:23
浏览 89

当引用const变量时,哪个是$ this或self或static?

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)

  • 写回答

2条回答 默认 最新

  • dongshi2141 2017-08-01 03:45
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波