문제

고 싶를 작성할 수 있 PHP 클래스는 것처럼 동작하는 배열을 사용하여 정상적인 배열에 대한 구문을 얻&설정입니다.

예를 들어(는 Foo PHP 클래스의 나를 만드는):

$foo = new Foo();

$foo['fooKey'] = 'foo value';

echo $foo['fooKey'];

내가 알고 있는 PHP 는 _get 및 _set 마술 방법이지만 당신을 실망시키지 않는 배열 표기법을 사용하여 액세스 항목입니다.Python 처리하여 그것의 과부하__getitem______________이며__setitem__.

하는 방법이 있나요 이렇게 PHP?는 경우에 분명한 차이를 느낄 수 있습니다,나는 실행 PHP5.2.

도움이 되었습니까?

해결책

을 연장하는 경우 ArrayObject 또 구현 ArrayAccess 다음을 할 수 있습니다.

다른 팁

Nope,주물 그 결과에서는 일반 PHP 배-을 잃고 어떤 기능의 ArrayObject-클래스 파생했습니다.이 체크아웃:

class CaseInsensitiveArray extends ArrayObject {
    public function __construct($input = array(), $flags = 0, $iterator_class =     'ArrayIterator') {
        if (isset($input) && is_array($input)) {
            $tmpargs = func_get_args();
            $tmpargs[0] = array_change_key_case($tmpargs[0], CASE_LOWER);
            return call_user_func_array(array('parent', __FUNCTION__), $tmp    args);
        }
        return call_user_func_array(array('parent', __FUNCTION__), func_get_args());
    }

    public function offsetExists($index) {
        if (is_string($index)) return parent::offsetExists(strtolower($index));
        return parent::offsetExists($index);
    }

    public function offsetGet($index) {
        if (is_string($index)) return parent::offsetGet(strtolower($index));
        return parent::offsetGet($index);
    }

    public function offsetSet($index, $value) {
        if (is_string($index)) return parent::offsetSet(strtolower($index, $value));
        return parent::offsetSet($index, $value);
    }

    public function offsetUnset($index) {
        if (is_string($index)) return parent::offsetUnset(strtolower($index));
        return parent::offsetUnset($index);
    }
}

$blah = new CaseInsensitiveArray(array(
    'A'=>'hello',
    'bcD'=>'goodbye',
    'efg'=>'Aloha',
));

echo "is array: ".is_array($blah)."\n";

print_r($blah);
print_r(array_keys($blah));

echo $blah['a']."\n";
echo $blah['BCD']."\n";
echo $blah['eFg']."\n";
echo $blah['A']."\n";

예상대로,array_keys()호출에 실패합니다.또한,is_array($blah)는 false 를 반환합니다.하지만 변경할 경우 생성자 라인:

$blah = (array)new CaseInsensitiveArray(array(

그럼 당신은 일반 PHP array(is_array($blah)true 를 반환하고 array_keys($blah)작동),그러나 모든 기능의 ArrayObject-서브 클래스 파생은 손실(이 경우에는 대소문자를 구분하는 키 더 이상 작동하).실행해 위의 코드는 두 가지고,당신이 무엇을 의미합니다.

PHP 해야를 제공하거나 기본 편에서는 키는 대소문자를 구분하지 않거나,ArrayObject 수 castable 을 배열을 잃지 않고 어떤 기능을 하위 클래스를 구현하는데 모든 배열 기능이 동 ArrayObject 인스턴스가 있습니다.

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