简体   繁体   English

PHP:如何创建常量的“树”

[英]PHP: how to create a “tree” of constants

I wonder if it is possible in PHP to create a "tree" of constants (without instantiating a tree of classes) ... let me explain what I would like to do (code is not correct) : 我想知道是否有可能在PHP中创建常量的“树”(而不实例化类树)...让我解释一下我想做什么(代码不正确):

abstract class logType {
   const Project = 1;
   const User = 2;
}
abstract class dbConstants {
   const logType = logType;
}

So that I use below in my code : 因此,我在代码中使用以下代码:

dbConstants::logType::Project

You can only use scalar data (integer, boolean, float and string), with PHP >5.6 you could also use scalar expressions, arrays and resources as the value of a constant as described here . 您只能使用标量数据(整数,布尔,float和string),与PHP> 5.6,你也可以使用标量表达式,数组和资源作为一个恒定的值作为描述在这里 With an array structure you could do something like this then: 使用数组结构,您可以执行以下操作:

abstract class logType
{
    const PROJECT = 1;
    const USER = 2;
}

abstract class dbConstants
{
    const logType = [
        logType::PROJECT,
        logType::USER
    ];
}

echo dbConstants::logType[logType::PROJECT];

Another approach would be to use a trait with public static members like this, if you do not want the class inheritances and reuse your code: 如果您不希望类继承并重用您的代码,则另一种方法是将trait与这样的public static成员一起使用:

trait logType
{
    public static $PROJECT = 1;
    public static $USER = 2;
}

abstract class dbConstants
{
    use logType;
}

echo dbConstants::$PROJECT;

Another way without the use of an array: 不使用数组的另一种方法:

class logType
{
    const PROJECT = 1;
    const USER = 2;
}

abstract class dbConstants
{
    public static $logType;

    public function __construct()
    {
        $this->logType = new logType();
    }
}

echo dbConstants::$logType::PROJECT;

In php 7: 在php 7中:

define('animals', [ 'dog', 'cat', 'bird' ]);

This will define a constant array. 这将定义一个常量数组。

In PHP 5.6 you can use const to declare a constant array. 在PHP 5.6中,可以使用const声明常量数组。

Both of these can contain more arrays to form a structure. 这两个都可以包含更多的数组以形成结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM