PHP 常量包含数组?

发布于 2024-08-02 07:21:11 字数 277 浏览 5 评论 0原文

这失败了:

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

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

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

//...

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

这似乎是不必要的努力。

This failed:

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

Apparently, constants can't hold arrays. What is the best way to get around this?

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

//...

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

This seems like unnecessary effort.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

影子是时光的心 2024-08-09 07:21:11

从 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'));

Since PHP 5.6, you can declare an array constant with const:

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

The short syntax works too, as you'd expect:

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

If you have PHP 7, you can finally use define(), just as you had first tried:

<?php
define('DEFAULT_ROLES', array('guy', 'development team'));
深海蓝天 2024-08-09 07:21:11

PHP 5.6+ 引入了 const 数组 - 请参阅 Andrea Faulds 的回答

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

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);

PHP 5.6+ introduced const arrays - see Andrea Faulds' answer.

You can also serialize your array and then put it into the constant:

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);
笑看君怀她人 2024-08-09 07:21:11

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

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

编辑

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

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

You can store them as static variables of a class:

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';

If you don't like the idea that the array can be changed by others, a getter might help:

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

EDIT

Since PHP5.4, it is even possible to access array values without the need for intermediate variables, i.e. the following works:

$x = Constants::getArray()['index'];
吲‖鸣 2024-08-09 07:21:11

如果您使用的是 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'));

If you are using PHP 5.6 or above, use Andrea Faulds answer

I am using it like this. I hope, it will help others.

config.php

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

In file, where I need constants.

require('config.php');
print_r(app::config('app_id'));
流星番茄 2024-08-09 07:21:11

这就是我用的。它与 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'

This is what I use. It is similar to the example provided by soulmerge, but this way you can get the full array or just a single value in the array.

class Constants {
    private static $array = array(0 => 'apple', 1 => 'orange');

    public static function getArray($index = false) {
        return $index !== false ? self::$array[$index] : self::$array;
    }
}

Use it like this:

Constants::getArray(); // Full array
// OR 
Constants::getArray(1); // Value of 1 which is 'orange'
友谊不毕业 2024-08-09 07:21:11

PHP 7+

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

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

echo ANIMALS[1]; // outputs "cat"

PHP 7+

As of PHP 7, you can just use the define() function to define a constant array :

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

echo ANIMALS[1]; // outputs "cat"
空城仅有旧梦在 2024-08-09 07:21:11

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

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

You can store it as a JSON string in a constant. And application point of view, JSON can be useful in other cases.

define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));    
$fruits = json_decode (FRUITS);    
var_dump($fruits);
末が日狂欢 2024-08-09 07:21:11

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

<?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;

I know it's a bit old question, but here is my solution:

<?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;

I defined it because I needed to store objects and arrays in constants so I installed also runkit to php so I could make the $const variable superglobal.

You can use it as $const->define("my_constant",array("my","values")); or just $const->my_constant = array("my","values");

To get the value just simply call $const->my_constant;

π浅易 2024-08-09 07:21:11

是的,您可以将数组定义为常量。从PHP 5.6开始,可以将常量定义为标量表达式,也可以定义数组常量。可以将常量定义为资源,但应避免这样做,因为它可能会导致意外结果。

<?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"
?>

参考此链接

祝您编码愉快。

Yes, You can define an array as constant. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

<?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"
?>

With the reference of this link

Have a happy coding.

夜光 2024-08-09 07:21:11

甚至可以使用关联数组......例如在类中。

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.

Can even work with Associative Arrays.. for example in a class.

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.
素衣风尘叹 2024-08-09 07:21:11

如果您使用 PHP 7 & 7+,你也可以像这样使用 fetch

define('TEAM', ['guy', 'development team']);
echo TEAM[0]; 
// output from system will be "guy"

if you're using PHP 7 & 7+, you can use fetch like this as well

define('TEAM', ['guy', 'development team']);
echo TEAM[0]; 
// output from system will be "guy"
悲欢浪云 2024-08-09 07:21:11

使用爆炸和内爆函数,我们可以临时提出一个解决方案:

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

这将回显电子邮件

如果你希望它进一步优化,你可以定义 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] ;
}

希望有帮助。快乐编码。

Using explode and implode function we can improvise a solution :

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

This will echo email.

If you want it to optimize it more you can define 2 functions to do the repetitive things for you like this :

//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] ;
}

Hope that helps . Happy coding .

椵侞 2024-08-09 07:21:11

执行某种 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() 功能,但无论如何您确实应该限制常量名称并避免全局变量。

Doing some sort of ser/deser or encode/decode trick seems ugly and requires you to remember what exactly you did when you are trying to use the constant. I think the class private static variable with accessor is a decent solution, but I'll do you one better. Just have a public static getter method that returns the definition of the constant array. This requires a minimum of extra code and the array definition cannot be accidentally modified.

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

initMyRoles( UserRoles::getDefaultRoles() );

If you want to really make it look like a defined constant you could give it an all caps name, but then it would be confusing to remember to add the '()' parentheses after the name.

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

//but, then the extra () looks weird...
initMyRoles( UserRoles::DEFAULT_ROLES() );

I suppose you could make the method global to be closer to the define() functionality you were asking for, but you really should scope the constant name anyhow and avoid globals.

北风几吹夏 2024-08-09 07:21:11

你可以这样定义

define('GENERIC_DOMAIN',json_encode(array(
    'gmail.com','gmail.co.in','yahoo.com'
)));

$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);

You can define like this

define('GENERIC_DOMAIN',json_encode(array(
    'gmail.com','gmail.co.in','yahoo.com'
)));

$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);
夜血缘 2024-08-09 07:21:11

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

Constants can only contain scalar values, I suggest you store the serialization (or JSON encoded representation) of the array.

您的好友蓝忘机已上羡 2024-08-09 07:21:11

如果您从 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;
}

If you are looking this from 2009, and you don't like AbstractSingletonFactoryGenerators, here are a few other options.

Remember, arrays are "copied" when assigned, or in this case, returned, so you are practically getting the same array every time. (See copy-on-write behaviour of arrays in 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;
}
亢潮 2024-08-09 07:21:11

警告如果您使用 spl_autoload_register(..) 函数并使用数组定义常量,则类注册顺序按字母顺序排列。我没有得到包含数组的常量,因为我在 B 类中声明了它,并想在 A 类中使用它,我认为常量是全局的,无论它们在哪里声明,但这是错误的!初始化常量的文件的顺序很重要。
希望有所帮助。

Warning if you use the spl_autoload_register(..) function and you define constants with arrays, the class registration order is in alphabetical order. I didn't get my constant containing an array because I declared it in class B and wanted to use it in my class A, I thought constants were global no matter where they are declared, but it is wrong ! The order of the files in which the constants are initialized is important.
Hoping to have helped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文