Everyone must know the stdClass class, But what about multi-dimensional arrays? We can't just convert like this,
This can be regarded as a base class of PHP5, providing a calling method similar to an array
You can convert an array through explicit methods into stdClass, and then access it as an object
Copy the PHP content to the 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 object calling method, which is convenient and smooth to write
2. Arrays are COPY values , the object can be over-referenced
3. It can implement some special functions (global static variables, we will talk about this later)
The following class will implement such a method,
As for where it can be used. You can use it
Copy the PHP content to Clipboard
PHP code:
$data = array(a1=>array(b1=>b1value,b2=>b2value,b3=>b3value));
$data = new map ($data);
// OBJ value
echo $data->a1->b1; // output: b1value
// OBJ assignment
$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);
}
// Value
public function __get($index){
return $this->offsetGet($index);
}
// Assignment
public function __set($index, $value){
is_array($value) && $value = new self($value);
$this-> offsetSet($index, $value);
}
// Whether
exists public function __isset($index){
return $this->offsetExists($index);
}
// Delete
public function __unset($index){
$this->offsetUnset($index);
}
// Convert For array type
public function toArray(){
$array = $this->getArrayCopy();
foreach ($array as &$value){
($value instanceof self) && $value = $value->toArray();
}
}
}
// Print as characters
public function __toString(){
return var_export($this->toArray(), true);
}
// Assign value based on index
public function put($index,$value){
is_array($ value) && $value = new self($value);
$this->offsetSet($index, $value);
}
// Get value based on index
public function get($index){
return $this->offsetGet($index);
}
}