문제

이것은 실패했다 :

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

분명히 상수는 배열을 유지할 수 없습니다. 이 문제를 해결하는 가장 좋은 방법은 무엇입니까?

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

//...

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

이것은 불필요한 노력처럼 보입니다.

도움이 되었습니까?

해결책

참고 : 이것은 허용 된 답변이지만 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 이후로 배열 상수를 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'));

클래스의 정적 변수로 저장할 수 있습니다.

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

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

이것이 제가 사용하는 것입니다. 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'

JSON 문자열로 상수로 저장할 수 있습니다. 그리고 적용 관점, JSON은 다른 경우에 유용 할 수 있습니다.

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

PHP 5.6부터 시작하면 사용을 사용하여 일정한 배열을 정의 할 수 있습니다. const 아래와 같은 키워드

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

다음과 같이 다른 요소에 액세스 할 수 있습니다.

echo DEFAULT_ROLES[1]; 
....

PHP 7부터 시작하여 일정한 배열을 사용하여 정의 할 수 있습니다. define 아래:

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

그리고 다른 요소는 이전과 같은 방식으로 액세스 할 수 있습니다.

나는 그것이 조금 오래된 질문이라는 것을 알고 있지만 여기 내 해결책이 있습니다.

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

객체와 배열을 상수에 저장해야했기 때문에 정의하여 PHP에 runkit을 설치하여 $ const 변수 Superglobal을 만들 수있었습니다.

당신은 그것을 사용할 수 있습니다 $const->define("my_constant",array("my","values")); 아니면 그냥 $const->my_constant = array("my","values");

값을 얻으려면 단순히 전화하십시오 $const->my_constant;

Explode and Implode 기능을 사용하여 솔루션을 즉흥적으로 할 수 있습니다.

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

이것은 반향 할 것입니다 email.

더 최적화하려면 더 많은 기능을 정의하여 다음과 같이 반복적 인 작업을 수행 할 수 있습니다.

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

도움이되기를 바랍니다. 행복한 코딩.

일종의 SER/DESER 또는 ENCODE/DECODE 트릭을 수행하는 것은 추악한 것처럼 보이며 상수를 사용하려고 할 때 정확히 무엇을했는지 기억해야합니다. 액세서가있는 클래스 개인 정적 변수는 괜찮은 솔루션이라고 생각하지만 더 잘하겠습니다. 상수 배열의 정의를 반환하는 공개 정적 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('GENERIC_DOMAIN',json_encode(array(
    'gmail.com','gmail.co.in','yahoo.com'
)));

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

PHP 7+

PHP 7 기준으로 만 사용할 수 있습니다. 정의하다() 일정한 배열을 정의하는 기능 :

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

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

연관 배열과 함께 작업 할 수도 있습니다. 예를 들어 클래스에서.

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.

예, 배열을 일정하게 정의 할 수 있습니다. 에서 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"
?>

참조와 함께 이 링크

행복한 코딩을하십시오.

2009 년부터 이것을보고 있고 초록이 factorygenerator를 좋아하지 않는다면 다음은 몇 가지 다른 옵션이 있습니다.

배열은 할당 되거나이 경우 반환 될 때 "복사"되므로 매번 동일한 배열을 얻습니다. (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;
}

상수는 스칼라 값 만 포함 할 수 있으며 배열의 직렬화 (또는 JSON 인코딩 된 표현)를 저장하는 것이 좋습니다.

Eyze에 동의합니다. 상수는 응용 프로그램의 전체 수명에 필요한 단일 값 인 경향이 있습니다. 이런 종류의 상수 대신 구성 파일을 사용하는 것에 대해 생각할 수 있습니다.

일정한 배열이 필요한 경우, 예를 들어 DB_NAME, DB_USER, DB_HOST 등과 같이 명명 규칙을 다소 모방 한 배열에 사용할 수 있습니다.

맞습니다. 상수, 스케일러와 널에만 배열을 사용할 수 없습니다. 상수에 배열을 사용한다는 아이디어는 나에게 약간 뒤로 보인다.

대신에 제안하는 것은 자신의 일정한 클래스를 정의하고 상수를 얻는 데 사용하는 것입니다.

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

배열을 일련의 상수로 폭발시킬 수도 있습니다. (꽤 오래된 학교 솔루션) 결국 배열은 끊임없는, 당신이 필요로하는 유일한 이유는 글로벌, 빠른, 조회 특정 키.

따라서 이것은 :

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

로 바뀔 것입니다 :

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

그렇습니다. 네임 스페이스 오염 (및이를 방지하기위한 많은 접두사)이 고려해야합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top