developer tip

PHP const 배열

optionbox 2020. 12. 24. 23:36
반응형

PHP const 배열


이것이 PHP에서 배열을 상수로 사용하는 유일한 방법입니까 아니면 다음과 같은 잘못된 코드입니까?

class MyClass
{
    private static $myArray = array('test1','test2','test3');

    public static function getMyArray()
    {
       return self::$myArray;
    } 
}

코드는 괜찮습니다-배열은 버전 5.6 이전의 PHP에서 상수로 선언 될 수 없으므로 정적 접근 방식이 아마도 가장 좋은 방법 일 것입니다. 주석을 통해이 변수를 상수로 표시하는 것을 고려해야합니다.

/** @const */
private static $myArray = array(...);

PHP 5.6.0 이상에서는 배열을 상수로 선언 할 수 있습니다.

const myArray = array(...);

PHP 5.6.0 (2014 년 8 월 28 일)부터 배열 상수를 정의 할 수 있습니다 ( PHP 5.6.0의 새로운 기능 참조 ).

class MyClass
{
    const MYARRAY = array('test1','test2','test3');

    public static function getMyArray()
    {
        /* use `self` to access class constants from inside the class definition. */
        return self::MYARRAY;
    } 
}

/* use the class name to access class constants from outside the class definition. */
echo MyClass::MYARRAY[0]; // echo 'test1'
echo MyClass::getMyArray()[1]; // echo 'test2'

$my = new MyClass();
echo $my->getMyArray()[2]; // echo 'test3'

PHP 7.0.0 (2015 년 12 월 3 일)에서는 define ()으로 배열 상수를 정의 할 수 있습니다. PHP 5.6에서는 const로만 정의 할 수 있습니다. ( PHP 7.0.0 새로운 기능 참조 )

define('MYARRAY', array('test1','test2','test3'));

나는 답을 찾기 위해이 스레드를 발견했습니다. 필요한 모든 함수를 통해 배열을 전달해야한다고 생각한 후 배열과 mysql에 대한 경험으로 인해 직렬화가 작동하는지 궁금해졌습니다. 물론 그렇습니다.

define("MYARRAY",     serialize($myarray));

function something() {
    $myarray= unserialize(MYARRAY);
}

정적으로 표시하는 것은 좋은 대안입니다. 다음은 일정한 동작 을 얻기 위해 정적 배열을 캡슐화하는 예입니다 .

class ArrayConstantExample {

    private static $consts = array(
        'CONST_MY_ARRAY' => array(
            1,2,3,4
        )
    );

    public static function constant($name) {
        return self::$consts[$name];
    }

}

var_dump( ArrayConstantExample::constant('CONST_MY_ARRAY') );

인쇄물:

array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) }

다음을 사용하는 것이 좋습니다.

class MyClass
{
    public static function getMyArray()
    {
       return array('test1','test2','test3');
    } 
}

이렇게하면 const 배열이 생기고 Class 자체의 메서드조차도 아무도 변경할 수 없다는 것을 보장합니다.

가능한 마이크로 최적화 (현재 PHP 컴파일러가 얼마나 최적화하는지 확실하지 않음) :

class MyClass
{
    public static function getMyArray()
    {
       static $myArray = array('test1','test2','test3');
       return $myArray;
    } 
}

상수 배열이 아닌 정적 배열을 만들었습니다 . 정적 변수는 변경 가능합니다. 상수는 변경할 수 없습니다. 당신의 코드는 나쁘지 않지만 의도 한대로 작동하지 않습니다.

In PHP 5.6, you can declare const arrays. Please see my previous explanation.

Perhaps you want something like this:

class MyClass
{
    const MY_ARRAY = array('test1','test2','test3');

    public function getMyArray()
    {
       return MY_ARRAY;
    } 
}

Note that constants have no $ prefix, which indicates their immutability. $foo is a variable; FOO is not. Additionally, constant names are always capitalized, at least in the programming languages I've been exposed to. This is not enforced by the compiler; it is simply an (almost?) universal coding style convention. Visibility keywords public, protected, and private do not apply to constants. Finally, static may or may apply depending on whether or not you want the function to be static.


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.

class foo {
   const KEYS = [1, 3, 6, 7];
}
//
echo foo::KEYS[0]; // 1

ReferenceURL : https://stackoverflow.com/questions/12129066/php-const-arrays

반응형