说我们有以下内容:
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;
)
我真的希望将常量放在另一个文件中,因为它在我的案例中很有意义。有没有办法在类的范围内声明常量?我知道在类定义中使用includes
或requires
是不可能的,所以我不知所措。
答案 0 :(得分:5)
最简单的可能性是在一个类中定义你的常量,让你的另一个类扩展该类。
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自动加载器,可以轻松将其拆分为两个不同的文件。
答案 1 :(得分:2)
如此简单的事情:
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');
但是,它不是很明确。配置中没有合同。
答案 2 :(得分:0)
简单地说,没有扩展到php就不可能。我最后只是在类文件中定义了自己的consts。