【问题标题】:Constant scope inside class method PHP类方法PHP内的常量范围
【发布时间】:2021-08-21 12:30:29
【问题描述】:
class A
{

    public const a = "Constant";

    public function getConstant()
    {
        echo a; //why is this undefined the 'const a' scope should be available for this block too like get function
    }

}

const b = "Constant";

function get()
{

    echo a;//'const b' scope is available for this block
}

get();

$obj = new A();

$obj->getConstant(); //Fatal error: Uncaught Error: Undefined constant "a"

【问题讨论】:

  • 为了访问类A中的常量a,你需要使用self::a。如果你想访问类外部的公共常量A,你可以使用A::a。为了使您的常量全局化,您需要在任何类之外定义它。
  • 我投票结束这个问题,因为答案是前面和中心in the manual

标签: php class methods scope constants


【解决方案1】:
class A {

public const a = "Constant";

public function getConstant()
{
    echo self::a;
}

}

https://www.php.net/manual/en/language.oop5.constants.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多