Странное поведение с массивом как статическим свойством класса - PullRequest
1 голос
/ 10 декабря 2011

Могу ли я иметь ассоциативный массив как свойство класса?

Я пытался, но я получаю очень странные результаты на что-то вроде этого:

class MyClass {
  public static $quality = array('blue' => 20, 'green' => 30, 'yellow' => 40);
  public $car = array();
  public $bus = array();

  function __construct() {
     foreach(self::$quality as $key => $value) {
         $this->car[$key] = $value;
         $this->bus[$key] = $value;
         echo $this->car[$key] . '<br />';
         echo $this->bus[$key] . '<br />';
     }
     foreach(self::$quality as $key => $value) {
         echo $this->car[$key] . ' - ' . $this->bus[$key] . '<br />';
     }
  }
}

Я ожидаю этот вывод:

20
20
30
30
40
40
40 - 40
30 - 30
20 - 20

но вместо этого я получаю:

20
20
30
3
40
4
20 - 4
30 - 4
40 - 4

Вот и все. Только зеленый и желтый автобус пропускают вторую цифру ...

И в другой точке моего класса, когда у меня что-то вроде этого:

$attrib = 'bus';
$index = 'blue';
echo $this->$attrib[$index];

Я получаю

Неопределенное свойство MyClass :: $ b

Есть какие-нибудь намеки на то, что я делаю неправильно? Или PHP не принимает ассоциативные массивы как свойства классов? Любая помощь будет принята с благодарностью.


Вот код, который я выделил. Если вы запустите этот PHP сам по себе, вы получите странное поведение ...

<code><?php
    ini_set('display_errors',1);
    error_reporting(E_ALL);

    class Session 
    {
        public static $per_page_count = array('photo' => 8 ,'book' => 20, 'road' => 30, 'lodge' => 30, 'tag' => 50);
        public $current_page = array();
        public $per_page = array();
        public $total_count = array();

        function __construct()
        {
            foreach (self::$per_page_count as $page_key => $page_count)
            {
                if (isset($this->per_page[$page_key])) 
                {
                    if ($this->per_page[$page_key] == '') $this->per_page[$page_key] = $page_count;
                }
                else  $this->per_page[$page_key] = $page_count;
                if (isset($this->current_page[$page_key]))
                {
                    if ($this->current_page[$page_key] == '') $this->current_page[$page_key] = 1;
                }
                else $this->current_page[$page_key] = 1;
                $this->total_count[$page_key] = 1;
            }
        }

        public function get_set($attribute,$index='',$value='')
        {
            echo '<br />before - '.$attribute.'-'.$index.'-'.$value.'<br />';
            if (trim($value) != '')
            {
                if (property_exists($this,$attribute))
                {
                    $this->$attribute['aaa'] = 50;
                    if ($index != '')
                    {
                        $_SESSION[$attribute][$index] = $value;
                        $this->$attribute[$index] = $value;
                    }
                    else
                        $_SESSION[$attribute] = $this->$attribute = $value;

                    $arraykey = array_keys($this->$attribute);
                }
            }
            else
            {
                if ($index != '')
                    return $this->$attribute[$index];
                else
                    return $this->$attribute;
            }
            echo '<pre>';
            print_r($this);
            echo '
'; echo '
after -'. $ attribute .'- '. $ index .'-'. $ value. '
'; echo '
variable -'. $ this -> $ attribute [$ index] .'- '. $ value.'
'; } } $ session = new Session (); $ Session-> get_set ( 'current_page', 'фото', 4); $ Session-> get_set ( 'TOTAL_COUNT', 'фото', 150); ?>

Внизу вы видите, что я вызываю get_set () дважды, и каждый раз вместо установки свойства внутри класса создается новое свойство.

Что я делаю не так? Спасибо за любую помощь.

1 Ответ

0 голосов
/ 10 декабря 2011

Неправильно:

$attrib = 'bus';
$index = 'blue';
echo $this->$attrib[$index];

Правильно:

$attrib = 'bus';
$index = 'blue';
$hash = $this->$attrib
echo $hash[$index];

Что происходит не в той версии? Во-первых, можно искать символ в строке по позиции. Например:

$str = 'abcdefg';
echo $str[1];  // outputs 'b'

$attrib[$index] оценивается первым. PHP обрабатывает $index как числовой индекс для строки $attrib, при этом $index преобразуется в число (в PHP 'blue' == 0). Начиная с $attrib[0] == 'b', PHP ищет $this->b, следовательно, ошибка Undefined property.

...