如何在 class(及其范围)中包含定义常量的文件

How to include a file that defines constants in a class (and it's scope)

假设我们有以下内容:

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();
    }

}

现在可以了,但是常量不是在 class (echo some::SOMECONST;) 的范围内定义的,而是在全局范围内 (echo SOMECONST;)

真的真的 想把常量放在另一个文件中,因为这对我来说很有意义。有没有办法在 class 范围内声明常量?我知道不可能在 class 定义中使用 includesrequires 所以我很茫然。

像这样简单的事情怎么样:

class Foo
{
    public $config;

    public __construct($config)
    {
        $this->config = $config;
        fun_stuff();
    }

    public function Bar()
    {
        echo $this->config['baz'];
    }

}

$foo = new Foo(include_once 'config.php');

config.php

<?php
return array('baz' => 'hello earth');

虽然不是很明确。配置上没有合同。

简而言之,没有 php 的扩展是不可能的。我最终只是在 class 文件中自己定义了常量。

最简单的方法是在一个 class 中定义常量,然后让另一个 class 扩展 class。

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 自动加载器,这可以很容易地分成两个不同的文件。