We all know the StdClass class,
This can be seen as a base class for PHP5, which provides an array-like calling method
An array can be converted to Stdclass by an explicit method, and then accessed by means of a pair of images
Copy PHP content to clipboard
PHP Code:
$a = new StdClass ();
$a->b = 1;
ECHP $a->b; Output:1
Arr->obj
$arr = Array (a, b);
$obj = (object) $arr;
Why not use arrays? Isn't it more convenient for PHP to use arrays?
1. I like to use the call method of the image, it is easy to write, smooth
2. The array is a copy value, which can be referenced
3. Some special functions can be implemented, (global static variable, this later)
But what about multidimensional arrays? We can't just change that.
The following class. This method will be implemented,
As to where it can be used. Everyone can play
Copy PHP content to clipboard
PHP Code:
$data = Array (A1=>array (B1=>b1value,b2=>b2value,b3=>b3value));
$data = new map ($data);
OBJ Fetch Value
Echo $data->a1->b1; Output:b1value
OBJ Assignment Value
$data->a1->b2 = Newb2value;
Echo
. $data->a1->b2; Output:newb2value
ARRAY value
Echo
. $data [A1][B3]; Output:b3value
FOREACH Loop
Output:b1=>b1value B2=>newb2value B3=>b3value
foreach ($data->a1 as $key = + $val) {
Echo
. $key. =>. $val;
}
Class Map
Copy PHP content to clipboard
PHP Code:
Class Map extends arrayobject{
Get Arrayobject Factor
Public function __construct (array $array = Array ()) {
foreach ($array as & $value) {
Is_array ($value) && $value = new self ($value);
}
Parent::__construct ($array);
}
Take value
Public Function __get ($index) {
return $this->offsetget ($index);
}
Assign value
Public Function __set ($index, $value) {
Is_array ($value) && $value = new self ($value);
$this->offsetset ($index, $value);
}
Whether there is
Public Function __isset ($index) {
return $this->offsetexists ($index);
}
Delete
Public Function __unset ($index) {
$this->offsetunset ($index);
}
Converting to an array type
Public Function ToArray () {
$array = $this->getarraycopy ();
foreach ($array as & $value) {
($value instanceof self) && $value = $value->toarray ();
}
return $array;
}
Print into characters
Public Function __tostring () {
Return Var_export ($this->toarray (), true);
}
Assigning values based on indexes
Public function put ($index, $value) {
Is_array ($value) && $value = new self ($value);
$this->offsetset ($index, $value);
}
Value based on index
Public function Get ($index) {
return $this->offsetget ($index);
}
}
http://www.bkjia.com/PHPjc/508295.html www.bkjia.com true http://www.bkjia.com/PHPjc/508295.html techarticle everyone knows the StdClass class, which can be seen as a base class for PHP5, provides an array-like calling method that can be used to convert an array into StdClass by an explicit method, and then pass ...