Can I have an associative array as a property of a class?
I have been trying but I get very strange results on something like this:
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 />';
}
}
}
I am expecting this output:
20
20
30
30
40
40
40 - 40
30 - 30
20 - 20
but instead, I'm getting:
20
20
30
3
40
4
20 - 4
30 - 4
40 - 4
That's it. Only green and yellow bus miss the second digit...
And in a different point in my class, when I have something like this:
$attrib = 'bus';
$index = 'blue';
echo $this->$attrib[$index];
I get
Undefined Property MyClass::$b
Any hints on what I'm doing wrong? Or PHP doesn't accept associative arrays as properties of classes? Any help will be greatly appreciated.
Here is the code I isolated. If you run this PHP by itself you should get the strange behavior...
<?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 '</pre>';
echo '<br />after - '.$attribute.'-'.$index.'-'.$value.'<br />';
echo '<br />variable - '.$this->$attribute[$index].'-'.$value.'<br />';
}
}
$session = new Session();
$session->get_set('current_page','photo',4);
$session->get_set('total_count','photo',150);
?>
At the bottom, you see that I call get_set() twice and each time, instead of setting the property inside the class, it creates a new property.
What am I doing wrong? A appreciate any help.