How to achieve the following requirements:
$data = Array (' x ' => ' xx ', ' y ' => ' yy ');
echo $data [' x '];//output xx
echo $data->x;//output XX
Method One: Constructs a class, realizes the Arrayaccess interface and the __get,__set magic method
Class Test implements Arrayaccess {
Private $data = null;
Public function __construct ($data) {
$this->data = $data;
}
Public Function Offsetget ($offset) {
Return ($this->offsetexists ($offset) $this->data[$offset]: null);
}
Public Function Offsetset ($offset, $value) {
$this->data[$offset] = $value;
}
Public Function offsetexists ($offset) {
return Isset ($this->data[$offset]);
}
Public Function Offsetunset ($offset) {
if ($this->offsetexists ($offset)) {
unset ($this->data[$offset]);
}
}
Public Function __get ($offset) {
Return ($this->offsetexists ($offset) $this->data[$offset]: null);
}
Public Function __set ($offset, $value) {
$this->data[$offset] = $value;
}
}
Test code
$data = Array (' x ' => ' x ', ' y ' => ' y ');
$t = new Test ($data);
printf ("Array mode access (\ $t [' x ']) output:%s <br/>", $t [' X ']);
printf ("Object mode access (\ $t->y) output:%s <br/>", $t->y);
Array method, Object-mode access
$t [' x1 '] = ' x1 ';
printf ("Array way assignment%s <br/>", "\ $t [' x1 ']= ' x1 ');
printf ("Object mode access (\ $t->x1) output:%s <br/>", $t->x1);
Object, array-mode access
$t->y1 = ' Y1 ';
printf ("Object method assignment%s <br/>", "\ $t->y1= ' y1 ');
printf ("Array-mode access (\ $t [' y1 ']) output:%s <br/>", $t [' Y1 ']);
Method Two
$data = Array (' x ' => ' x ', ' y ' => ' y ');
$t = new Arrayobject ($data, arrayobject::array_as_props);
printf ("Array mode access (\ $t [' x ']) output:%s <br/>", $t [' X ']);
printf ("Object mode access (\ $t->y) output:%s <br/>", $t->y);
Array method, Object-mode access
$t [' x1 '] = ' x1 ';
printf ("Array way assignment%s <br/>", "\ $t [' x1 ']= ' x1 ');
printf ("Object mode access (\ $t->x1) output:%s <br/>", $t->x1);
Object, array-mode access
$t->y1 = ' Y1 ';
printf ("Object method assignment%s <br/>", "\ $t->y1= ' y1 ');
printf ("Array-mode access (\ $t [' y1 ']) output:%s <br/>", $t [' Y1 ']);
Test results