📜 ⬆️ ⬇️

Nested arrays and magic methods

Probably everyone knows about the magic (magic) methods in PHP, and specifically __get and __set methods. However, there is an unpleasant feature if you need to change the value of the nested array. To solve this problem there is a simple and elegant solution.


Consider the following class:
class MyClass {
protected $ data = array ( 'some' => array ( 'sub' => 'data' ) ) ;

public function __set ( $ name , $ value ) {
$ this -> data [ $ name ] = $ value ;
}
public function __get ( $ name ) {
return $ this -> data [ $ name ] ;
}
}

')
If you try to change the value of the sub key of some $ data array like this:

$ my = new MyClass ( ) ;

$ my -> some [ 'sub' ] = 'test' ; // trying to change the value

echo $ my -> some [ 'sub' ] ; // displays 'data'


Notice will come out:
Notice: Indirect modification of overloaded property MyClass :: $ some has no effect


To solve the problem, we will write another class (I call it ActiveArray, since it is part of my ActiveRecord):

class ActiveArray {
protected $ array ;

public function __construct ( $ array ) {
$ this -> array = & $ array ;
}

public function __set ( $ name , $ value ) {
$ this -> array [ $ name ] = $ value ;
}

public function __get ( $ name ) {
if ( is_array ( $ this -> array [ $ name ] ) )
return new self ( & $ this -> array [ $ name ] ) ;
else
return $ this -> array [ $ name ] ;
}
}


And slightly modify the __get method of the class MyClass:
public function __get ( $ name ) {
if ( is_array ( $ this -> data [ $ name ] ) )
return new ActiveArray ( & $ this -> data [ $ name ] ) ;
else
return $ this -> data [ $ name ] ;
}


Now you can access the nested arrays like this:
$ my -> some -> sub = 'test' ;
echo $ my -> some -> sub ; // displays 'test'

$ my -> some = array ( 'abc' => 123 ) ;
echo $ my -> some -> abc ; // will print '123'


Thanks for attention!

Source: https://habr.com/ru/post/103834/


All Articles