加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何包含一个在类中定义常量的文件(以及它的作用域)

发布时间:2020-12-13 17:49:43 所属栏目:PHP教程 来源:网络整理
导读:假设我们有以下内容: some.class.php class{ public __construct() { fun_stuff(); }} configuration.inc const SOMECONST = 1;const SOMEOTHERCONST = 2; 我希望做这样的事情: some.class.php class{ public __construct() { include_once(configuration.
假设我们有以下内容:

some.class.php

class
{
    public __construct()
    {
        fun_stuff();
    }

}

configuration.inc

const SOMECONST = 1;
const SOMEOTHERCONST = 2;

我希望做这样的事情:

some.class.php

class
{
    public __construct()
    {
        include_once(configuration.inc);
        fun_stuff();
    }

}

现在这个工作,但是常量不是在类的范围内定义的(echo some :: SOMECONST;)而是在全局范围内(echo SOMECONST;)

我真的很想把常量放在另一个文件中,因为它在我的情况下很有意义.有没有办法在类的范围内声明常量?我知道在类定义中使用包含或要求是不可能的,所以我不知所措.

解决方法

最简单的可能性是在一个类中定义常量,让其他类扩展该类.

class myClassConstant {
  const SOMECONST = 1;
  const SOMEOTHERCONST = 2;
}

class myClass extends myClassConstant {

  public function __construct() {
    echo self::SOMECONST . ' + ' . self::SOMEOTHERCONST . ' = 3';
  }
}

$obj = new myClass(); // Output: 1 + 2 = 3

如果您使用的是php autoloader,则可以轻松将其拆分为两个不同的文件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读