실패했습니다 :
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'];
답변
나는 이것을 이렇게 사용하고 있습니다. 다른 사람들을 도울 것입니다.
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'
]);
이전과 같은 방식으로 다른 요소에 액세스 할 수 있습니다.
