首页 文章

包含数组的PHP常量?

提问于
浏览
364

这失败了:

define('DEFAULT_ROLES', array('guy', 'development team'));

显然,常量不能保存数组 . 解决这个问题的最佳方法是什么?

define('DEFAULT_ROLES', 'guy|development team');

//...

$default = explode('|', DEFAULT_ROLES);

这似乎是不必要的努力 .

20 回答

  • 477

    NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.

    您还可以序列化您的数组,然后将其放入常量:

    # define constant, serialize array
    define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
    
    # use it
    $my_fruits = unserialize (FRUITS);
    
  • 40

    从PHP 5.6开始,您可以使用 const 声明一个数组常量:

    <?php
    const DEFAULT_ROLES = array('guy', 'development team');
    

    正如您所期望的那样,短语法也有效:

    <?php
    const DEFAULT_ROLES = ['guy', 'development team'];
    

    如果你有PHP 7,你最终可以使用 define() ,就像你第一次尝试一样:

    <?php
    define('DEFAULT_ROLES', array('guy', 'development team'));
    
  • -2

    您可以将它们存储为类的静态变量:

    class Constants {
        public static $array = array('guy', 'development team');
    }
    # Warning: array can be changed lateron, so this is not a real constant value:
    Constants::$array[] = 'newValue';
    

    如果您不喜欢其他人可以更改阵列的想法,那么getter可能有所帮助:

    class Constants {
        private static $array = array('guy', 'development team');
        public static function getArray() {
            return self::$array;
        }
    }
    $constantArray = Constants::getArray();
    

    EDIT

    从PHP5.4开始,甚至可以访问数组值而无需中间变量,即以下工作:

    $x = Constants::getArray()['index'];
    
  • -1

    如果您使用的是PHP 5.6或更高版本,请使用Andrea Faulds的答案

    我这样用它 . 我希望,它会帮助别人 .

    config.php

    class app{
        private static $options = array(
            'app_id' => 'hello',
        );
        public static function config($key){
            return self::$options[$key];
        }
    }
    

    在文件中,我需要常量 .

    require('config.php');
    print_r(app::config('app_id'));
    
  • 2

    这就是我使用的 . 它类似于soulmerge提供的示例,但是这样您就可以获得完整数组或数组中的单个值 .

    class Constants {
        private static $array = array(0 => 'apple', 1 => 'orange');
    
        public static function getArray($index = false) {
            return $index !== false ? self::$array[$index] : self::$array;
        }
    }
    

    像这样用它:

    Constants::getArray(); // Full array
    // OR 
    Constants::getArray(1); // Value of 1 which is 'orange'
    
  • 2

    您可以将它作为JSON字符串存储在常量中 . 从应用的角度来看,JSON在其他情况下可能很有用 .

    define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));    
    $fruits = json_decode (FRUITS);    
    var_dump($fruits);
    
  • 5

    从PHP 5.6开始,您可以使用 const 关键字定义常量数组,如下所示

    const DEFAULT_ROLES = ['test', 'development', 'team'];
    

    可以访问不同的元素,如下所示:

    echo DEFAULT_ROLES[1]; 
    ....
    

    从PHP 7开始,可以使用 define 定义常量数组,如下所示:

    define('DEFAULT_ROLES', [
        'test',
        'development',
        'team'
    ]);
    

    并且可以像以前一样访问不同的元素 .

  • 8

    我知道这是一个有点老问题,但这是我的解决方案:

    <?php
    class Constant {
    
        private $data = [];
    
        public function define($constant, $value) {
            if (!isset($this->data[$constant])) {
                $this->data[$constant] = $value;
            } else {
                trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
            }
        }
    
        public function __get($constant) {
            if (isset($this->data[$constant])) {
                return $this->data[$constant];
            } else {
                trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
                return $constant;
            }
        }
    
        public function __set($constant,$value) {
            $this->define($constant, $value);
        }
    
    }
    $const = new Constant;
    

    我定义它是因为我需要在常量中存储对象和数组,所以我也将runkit安装到php,所以我可以使$ const变量超全局 .

    您可以将其用作 $const->define("my_constant",array("my","values")); 或仅用 $const->my_constant = array("my","values");

    要获得该值,只需调用 $const->my_constant;

  • -2

    使用爆炸和内爆功能,我们可以即兴创作解决方案:

    $array = array('lastname', 'email', 'phone');
    define('DEFAULT_ROLES', implode (',' , $array));
    echo explode(',' ,DEFAULT_ROLES ) [1];
    

    这将回应 email .

    如果你想让它更优化它你可以定义2个函数来为你做重复的事情:

    //function to define constant
    function custom_define ($const , $array) {
        define($const, implode (',' , $array));
    }
    
    //function to access constant  
    function return_by_index ($index,$const = DEFAULT_ROLES) {
                $explodedResult = explode(',' ,$const ) [$index];
        if (isset ($explodedResult))
            return explode(',' ,$const ) [$index] ;
    }
    

    希望有所帮助 . 快乐的编码 .

  • 12

    做某种ser / deser或编码/解码技巧似乎很难看,并且要求你记住在尝试使用常量时你究竟做了什么 . 我认为带有访问器的类私有静态变量是一个不错的解决方案,但我会做得更好 . 只需要一个返回常量数组定义的公共静态getter方法 . 这需要最少的额外代码,并且不能意外地修改数组定义 .

    class UserRoles {
        public static function getDefaultRoles() {
            return array('guy', 'development team');
        }
    }
    
    initMyRoles( UserRoles::getDefaultRoles() );
    

    如果你想让它看起来像一个定义的常量你可以给它一个全部大写名称,但是记住在名字后添加'()'括号会很困惑 .

    class UserRoles {
        public static function DEFAULT_ROLES() { return array('guy', 'development team'); }
    }
    
    //but, then the extra () looks weird...
    initMyRoles( UserRoles::DEFAULT_ROLES() );
    

    我想你可以使方法全局更接近你所要求的define()功能,但你真的应该使用常量名称作为范围并避免使用全局变量 .

  • 0

    你可以这样定义

    define('GENERIC_DOMAIN',json_encode(array(
        'gmail.com','gmail.co.in','yahoo.com'
    )));
    
    $domains = json_decode(GENERIC_DOMAIN);
    var_dump($domains);
    
  • 2

    是的,您可以将数组定义为常量 . 从 PHP 5.6 onwards 开始,可以将常量定义为标量表达式,它也是 possible to define an array constant . 可以将常量定义为资源,但应该避免,因为它可能会导致意外的结果 .

    <?php
        // Works as of PHP 5.3.0
        const CONSTANT = 'Hello World';
        echo CONSTANT;
    
        // Works as of PHP 5.6.0
        const ANOTHER_CONST = CONSTANT.'; Goodbye World';
        echo ANOTHER_CONST;
    
        const ANIMALS = array('dog', 'cat', 'bird');
        echo ANIMALS[1]; // outputs "cat"
    
        // Works as of PHP 7
        define('ANIMALS', array(
            'dog',
            'cat',
            'bird'
        ));
        echo ANIMALS[1]; // outputs "cat"
    ?>
    

    参考this link

    有一个快乐的编码 .

  • 1

    PHP 7

    从PHP 7开始,您只需使用define()函数来定义常量数组:

    define('ANIMALS', [
        'dog',
        'cat',
        'bird'
    ]);
    
    echo ANIMALS[1]; // outputs "cat"
    
  • 3

    甚至可以使用Associative Arrays ..例如在类中 .

    class Test {
    
        const 
            CAN = [
                "can bark", "can meow", "can fly"
            ],
            ANIMALS = [
                self::CAN[0] => "dog",
                self::CAN[1] => "cat",
                self::CAN[2] => "bird"
            ];
    
        static function noParameter() {
            return self::ANIMALS[self::CAN[0]];
        }
    
        static function withParameter($which, $animal) {
            return "who {$which}? a {$animal}.";
        }
    
    }
    
    echo Test::noParameter() . "s " . Test::CAN[0] . ".<br>";
    echo Test::withParameter(
        array_keys(Test::ANIMALS)[2], Test::ANIMALS["can fly"]
    );
    
    // dogs can bark.
    // who can fly? a bird.
    
  • 139

    常量只能包含标量值,我建议您存储数组的序列化(或JSON编码表示) .

  • -2

    如果你从2009年开始看这个,并且你不喜欢AbstractSingletonFactoryGenerators,这里有一些其他的选择 .

    请记住,数组在分配时会被“复制”,或者在这种情况下被返回,因此每次都可以获得相同的数组 . (请参阅PHP中数组的写时复制行为 . )

    function FRUITS_ARRAY(){
      return array('chicken', 'mushroom', 'dirt');
    }
    
    function FRUITS_ARRAY(){
      static $array = array('chicken', 'mushroom', 'dirt');
      return $array;
    }
    
    function WHAT_ANIMAL( $key ){
      static $array = (
        'Merrick' => 'Elephant',
        'Sprague' => 'Skeleton',
        'Shaun'   => 'Sheep',
      );
      return $array[ $key ];
    }
    
    function ANIMAL( $key = null ){
      static $array = (
        'Merrick' => 'Elephant',
        'Sprague' => 'Skeleton',
        'Shaun'   => 'Sheep',
      );
      return $key !== null ? $array[ $key ] : $array;
    }
    
  • 1

    我同意eyze,常量往往是应用程序整个生命周期所需的单值 . 您可能会考虑使用配置文件而不是常量来进行此类操作 .

    如果您确实需要常量数组,则可以使用命名约定来模拟数组:例如DB_Name,DB_USER,DB_HOST等 .

  • 1

    这是正确的,你不能使用数组作为常量,只能使用scaler和null . 将数组用于常量的想法似乎有点倒退 .

    我建议做的是定义你自己的常量类并使用它来获得常量 .

  • 709
    define('MY_ARRAY_CONSTANT_DELIMETER', '|');       
    define('MY_ARRAY',implode(MY_ARRAY_CONSTANT_DELIMETER,array(1,2,3,4)));
    
    //retrieving the array
    $my_array = explode(MY_ARRAY_CONSTANT_DELIMETER, MY_ARRAY);
    
  • 0

    您也可以将数组分解为一系列常量 . (一个相当古老的学校解决方案)毕竟,数组是恒定的,所以你唯一的原因需要它,是某些键的 global, fast, lookup .

    因此:

    define('DEFAULT_ROLES', array('guy', 'development team'));
    

    会变成:

    define('DEFAULT_ROLES_0', 'guy');
    define('DEFAULT_ROLES_1', 'development team');
    

    是的,要考虑名称空间污染(以及许多防止它的前缀) .

相关问题