Appending a protected Object with an array
I add more fields then below I am trying to append the years() output to an options list of an HTML select / dropdown. to do this I need to append $cmb_team_members->meta_box[‘fields’][‘_cmb_start_year’][‘options’] with the output array from the function years() . Below is where I am trying to extend CMB2 class which is protected with the years() output.
class yearsClass extends CMB2 < public function __set($name, $value) < $this->$cmb_team_members->meta_box['fields']['_cmb_start_year']['options'] = years(); > >
I know I am doing this completely wrong but I can’t seem to crack this. Any help would be appreciated. I have years defined in my functions.php file and it outputs:
array( 2015 => 2015, 2014 => 2014 )
CMB2 Object ( [cmb_id:protected] => team_member_metabox [meta_box:protected] => Array ( [id] => team_member_metabox [title] => Team Member Metabox [type] => [object_types] => Array ( [0] => post_type_teammember ) [context] => normal [priority] => high [show_names] => 1 [show_on_cb] => [show_on] => Array ( ) [cmb_styles] => 1 [enqueue_js] => 1 [fields] => Array ( [_cmb2_division] => Array ( [name] => Division [desc] => The division of the company this person works in (These can be edited in the Revolution Group theme options) [id] => _cmb2_division [type] => select [options] => Array ( ) ) [_cmb2_photo] => Array ( [name] => Photo [desc] => [id] => _cmb2_photo [type] => file ) [_cmb2_position] => Array ( [name] => Position [desc] => Job position [id] => _cmb2_position [type] => text ) [_cmb2_email] => Array ( [name] => Email [desc] => Email address [id] => _cmb2_email [type] => text_email ) [_cmb2_bio] => Array ( [name] => Bio [desc] => [id] => _cmb2_bio [type] => wysiwyg [options] => Array ( [media_buttons] => 1 [textarea_rows] => 5 ) ) [_cmb2_start_year] => Array ( [name] => Year Started [desc] => The year the team member started with Revolution Group [id] => _cmb2_start_year [type] => select [options] => Array ( ) ) [_cmb2_certifications_repeat_group] => Array ( [id] => _cmb2_certifications_repeat_group [type] => group [description] => Certifications (These can be edited in the Revolution Group theme options) [options] => Array ( [group_title] => Certification [add_button] => Add Another Certification [remove_button] => Remove Certification [sortable] => 1 ) [fields] => Array ( [certification] => Array ( [name] => Certification [description] => Please select [id] => _cmb2_certification [type] => select [options] => Array ( ) ) [certification_year] => Array ( [name] => Year Obtained [description] => The year this certification was aquired [id] => _cmb2_certification_year [type] => select [options] => Array ( ) ) ) ) [_cmb2_skills_repeat_group] => Array ( [id] => _cmb2_skills_repeat_group [type] => group [description] => Skills (These can be edited in the Revolution Group theme options) [options] => Array ( [group_title] => Skill [add_button] => Add Another Skill [remove_button] => Remove Skill [sortable] => 1 ) [fields] => Array ( [skill] => Array ( [name] => Skill [description] => Please select [id] => _cmb2_skill [type] => select [options] => Array ( ) ) ) ) [_cmb2_fun_fact] => Array ( [name] => Fun Fact [desc] => [id] => _cmb2_fun_fact [type] => wysiwyg [options] => Array ( [media_buttons] => 1 [textarea_rows] => 5 ) ) [_cmb2_order] => Array ( [name] => Order [desc] => Order that the team member should be displayed. The lower the number the hghter on the list when displayed [id] => _cmb2_order [type] => text ) ) [hookup] => 1 [save_fields] => 1 [closed] => [new_user_section] => add-new-user ) [object_id:protected] => 0 [object_type:protected] => post [mb_object_type:protected] => post [updated:protected] => Array ( ) [mb_defaults:protected] => Array ( [id] => [title] => [type] => [object_types] => Array ( ) [context] => normal [priority] => high [show_names] => 1 [show_on_cb] => [show_on] => Array ( ) [cmb_styles] => 1 [enqueue_js] => 1 [fields] => Array ( ) [hookup] => 1 [save_fields] => 1 [closed] => [new_user_section] => add-new-user ) [fields:protected] => Array ( ) [hidden_fields:protected] => Array ( ) [data_to_save] => Array ( ) [generated_nonce:protected] =>
The ArrayObject class
Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).
ArrayObject::ARRAY_AS_PROPS
Entries can be accessed as properties (read and write).
Table of Contents
- ArrayObject::append — Appends the value
- ArrayObject::asort — Sort the entries by value
- ArrayObject::__construct — Construct a new array object
- ArrayObject::count — Get the number of public properties in the ArrayObject
- ArrayObject::exchangeArray — Exchange the array for another one
- ArrayObject::getArrayCopy — Creates a copy of the ArrayObject
- ArrayObject::getFlags — Gets the behavior flags
- ArrayObject::getIterator — Create a new iterator from an ArrayObject instance
- ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject
- ArrayObject::ksort — Sort the entries by key
- ArrayObject::natcasesort — Sort an array using a case insensitive «natural order» algorithm
- ArrayObject::natsort — Sort entries using a «natural order» algorithm
- ArrayObject::offsetExists — Returns whether the requested index exists
- ArrayObject::offsetGet — Returns the value at the specified index
- ArrayObject::offsetSet — Sets the value at the specified index to newval
- ArrayObject::offsetUnset — Unsets the value at the specified index
- ArrayObject::serialize — Serialize an ArrayObject
- ArrayObject::setFlags — Sets the behavior flags
- ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject
- ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association
- ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function
- ArrayObject::unserialize — Unserialize an ArrayObject
User Contributed Notes 22 notes
As you know ArrayObject is not an array so you can’t use the built in array functions. Here’s a trick around that:
Extend the ArrayObject class with your own and implement this magic method:
public function __call ( $func , $argv )
if (! is_callable ( $func ) || substr ( $func , 0 , 6 ) !== ‘array_’ )
throw new BadMethodCallException ( __CLASS__ . ‘->’ . $func );
>
return call_user_func_array ( $func , array_merge (array( $this -> getArrayCopy ()), $argv ));
>
?>
Now you can do this with any array_* function:
$yourObject -> array_keys ();
?>
— Don’t forget to ommit the first parameter — it’s automatic!
Note: You might want to write your own functions if you’re working with large sets of data.
There is a better explanation about the ArrayObject flags (STD_PROP_LIST and ARRAY_AS_PROPS) right here:
If you need the last key of your collection use:
array_key_last ( $this -> getArrayCopy ())
?>
In an extending class it could look like:
class Collection extends ArrayObject
public function lastKey (): int
return array_key_last ( $this -> getArrayCopy ());
>
>
?>
If you want to use any type safe collection:
class BookCollection extends Collection
public function add ( Book $book ) : void
$this -> offsetSet ( $book -> id , $book );
>
// note the return type «Book»
public function get ( int $bookId ) : Book
$this -> offsetGet ( $bookId );
>
>
?>
Generally variable $this can’t be used as an array within an object context. For example, following code piece would cause a fatal error:
class TestThis public function __set ( $name , $val ) $this [ $name ] = $val ;
>
public function __get ( $name ) return $this [ $name ];
>
>
$obj = new TestThis ();
$obj -> a = ‘aaa’ ;
echo $obj -> a . «\n» ;
?>
But things are different when $this is used in an ArrayObject object. e.g., following code piece are valid:
class TestArrayObject extends ArrayObject <
public function __set ( $name , $val ) $this [ $name ] = $val ;
>
public function __get ( $name ) return $this [ $name ];
>
>
$obj = new TestArrayObject ();
$obj -> a = ‘aaa’ ;
echo $obj -> a . «\n» ;
?>
I found the description of STD_PROP_LIST a bit vague, so I put together a simple demonstration to show its behavior:
$a = new ArrayObject (array(), ArrayObject :: STD_PROP_LIST );
$a [ ‘arr’ ] = ‘array data’ ;
$a -> prop = ‘prop data’ ;
$b = new ArrayObject ();
$b [ ‘arr’ ] = ‘array data’ ;
$b -> prop = ‘prop data’ ;
// ArrayObject Object
// (
// [prop] => prop data
// )
print_r ( $a );
// ArrayObject Object
// (
// [arr] => array data
// )
print_r ( $b );
// Example STD_PROP_LIST and ARRAY_AS_PROP combined
$ao = new ArrayObject ();
$ao -> setFlags ( ArrayObject :: STD_PROP_LIST | ArrayObject :: ARRAY_AS_PROPS );
$ao -> prop = ‘prop data’ ;
$ao [ ‘arr’ ] = ‘array data’ ;
ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[prop] => prop data
[arr] => array data
)
I don’t believe the same performance is true since PHP 5.3. Using the same fill, read_key and foreach approach on both native arrays and ArrayObjects with 10000 keys I get the following
array() fill 0.013101
array() read 0.008685
array() foreach 0.004319
ArrayObject fill 0.014136
ArrayObject read 0.010003
ArrayObject foreach 3.454612
array() fill 0.010395
array() read 0.005933
array() foreach 0.001903
ArrayObject fill 0.010598
ArrayObject read 0.006387
ArrayObject foreach 0.003451
This was the code I used for both, an array or ArrayObject is passed into each of the functions. Again PEAR::Benchmark was used to get the results.
If you want to use built-in array function with ArrayObject, store the iterator instance and return the value as reference in offsetGet.
$this -> iterator = $this -> getIterator ();
parent :: __construct ( $data );
>
To implement array-style appending (e.g. «$object[] = ‘foo’;») in your own class implementing the ArrayAccess _interface_, all you need do is check if the key passed to your implementation of offsetSet() is NULL. Something like the following.
class MyArrayObject implements ArrayAccess
/**
* @see ArrayAccess::offsetSet()
*/
public function offsetSet ( $p_key , $p_value ) if ( is_null ( $p_key )) $this -> aValue [] = $p_value ;
>
else $this -> aValue [ $p_key ] = $p_value ;
>
>
If you plan to derive your own class from ArrayObject, and wish to maintain complete ArrayObject functionality (such as being able to cast to an array), it is necessary to use ArrayObject’s own private property «storage».
Since that is impossible to do directly, you must use ArrayObject’s offset methods to manipulate it indirectly.
As a side benefit, this means you inherit all the iteration and other functions in complete working order.
This may sound obvious to someone who has never implemented their own ArrayObject class. but it is far from so.
class MyArrayObject extends ArrayObject <
static $debugLevel = 2 ;
static public function sdprintf () <
if (static:: $debugLevel > 1 ) <
call_user_func_array ( «printf» , func_get_args ());
>
>
public function offsetGet ( $name ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
public function offsetSet ( $name , $value ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
public function offsetExists ( $name ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
public function offsetUnset ( $name ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
>
$mao = new MyArrayObject ();
$mao [ «name» ] = «bob» ;
$mao [ «friend» ] = «jane» ;
print_r ((array) $mao );
offsetSet(name,bob)
offsetSet(friend,jane)
Array
(
[name] => bob
[friend] => jane
) */
?>
If you wish to use the «Array as Properties» flag, you simply need to include this in your constructor:
This will allow you to do things such as the below example, without overriding __get or __set .
$mao -> name = «Phil» ;
echo $mao [ «name» ]; /* Outputs «Phil» */
?>