Skip to content

Instantly share code, notes, and snippets.

@lsauer
Created October 11, 2011 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsauer/1278532 to your computer and use it in GitHub Desktop.
Save lsauer/1278532 to your computer and use it in GitHub Desktop.
PHP accessing numeric properties from an object to allow e.g. obj(explode("-","my-test-test"))->_0
//lo sauer, 2011 - lsauer.com
PHP variable names can't start with a digit. As such non-associative array conversion can pose a problem.
Additionally stdClass does not implement ArrayAccess - as PHP's base class.
//note: this is not serialized php code
$var = stdClass Object
(
[0] => stdClass Object
(
['my'] => 1442,
['data'] => "sample string"
)
);
//this will fail in PHP 5+
print_r( $var->{'0'}->data );
//PHP's problem is the ceasation of constant variable setting and reading:
//since neither this
explode("-","my-test-test")[0] nor
explode("-","my-test-test"){'0'} nor
((object)explode("-","my-test-test"))->{'0'};... will work!
//solution: object-casting wrapper
function obj($arr){return (object) $arr;}
//you should then be able to access properties directly as in most modern programming languages
print_r(obj(explode("-","my-test-test"))->{0});
//in php >5 this will however no longer work:
//->tries to access stdClass::$0 within the obj
//solution: object-casting wrapper which prefixes the indexes
function obj($arr){ for($i=count($arr), $cp=array(); $i; $i--,$cp['_'.$i]=$arr[$i]); return (object) $cp;}
obj(explode("-","my-test-test"))->_0
returns 'my'
In this case there we could have gotten the same result with ■array_shift or ■each however in complex situations
an OOP approach holds advantages, above all is the clear left-to-right-reading of how the object 'evolved' in the programming code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment