Last active
December 26, 2015 18:19
-
-
Save mrded/7193844 to your computer and use it in GitHub Desktop.
PHP: ArrayObject examples.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$foo = isset($array['foo']) ? $array['foo'] : null; | |
$bar = isset($array['bar']) ? $array['bar'] : null; | |
# With php notices | |
$foo = $array['foo'] ? : null; | |
$bar = $array['bar'] ? : null; | |
# DefaultingArrayObject | |
$array = new DefaultingArrayObject($array); | |
$foo = $array['foo']; | |
$bar = $array['bar']; | |
# PHP 5.4+ | |
$array = new DefaultingArrayObject($array); | |
$foo = $array->setDefault('default for foo')['foo']; | |
$bar = $array->setDefault('default for bar')['bar']; | |
$array = new DefaultingArrayObject($array); | |
$foo = $array->get('foo', 'default for foo'); | |
$bar = $array->get('bar', 'default for bar'); | |
# ExceptionArrayObject | |
$array = new ExceptionArrayObject($array); | |
try { | |
// logic that uses foo, bar and baz array values | |
} catch (UndefinedIndexException $e) { | |
// logic that does not use foo, bar and baz array values | |
} | |
# CallbackArrayObject | |
$array = new ConfigurableCallbackArrayObject([ | |
'foo' => function($config) { | |
return 'foo ' . $config['foo']; | |
}, | |
'bar' => function($config) { | |
return 'bar ' . $config['bar']; | |
}, | |
]); | |
$array->setConfig(['foo' => 123, 'bar' => 321]); | |
$foo = $array['foo']; // "foo 123" | |
$bar = $array['bar']; // "bar 321" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment