簡體   English   中英

如何在類中包含定義常量的文件(及其范圍)

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

}

現在這個工作,但是常量不是在類的范圍內定義的( echo some::SOMECONST; )而是在全局范圍內( echo SOMECONST;

真的很想把常量放在另一個文件中,因為它在我的情況下很有意義。 有沒有辦法在類的范圍內聲明常量? 我知道在類定義中使用includesrequires是不可能的,所以我不知所措。

最簡單的可能性是在一個類中定義常量,讓其他類擴展該類。

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,則可以輕松將其拆分為兩個不同的文件。

這樣簡單的事情怎么樣:

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的擴展是不可能的。 我最后只是在類文件中定義了自己的consts。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM