Phillip Pearson - web + electronics notes

tech notes and web hackery from a new zealander who was vaguely useful on the web back in 2002 (see: python community server, the blogging ecosystem, the new zealand coffee review, the internet topic exchange).

2008-7-24

PHP hackery: quick and dirty anonymous objects

Here's an awesome trick: you can cast arrays to objects in PHP then access them like objects. The brilliant part about it is that it appears to make them act like objects, i.e. $b = $a makes $a and $b point to the same object (like pretty much every other dynamic language) rather than copying $a.

$ php
<?php

$a = array(1, 2, 3);
$b = $a;
$a[] = 4;
$b[] = 5;

$c = (object)$a;
$d = $c;
$c->foo = "bar";
$d->baz = "boz";

echo '$a: '; var_dump($a);
echo '$b: '; var_dump($b);
echo '$c: '; var_dump($c);
echo '$d: '; var_dump($d);
?>
$a: array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}
$b: array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(5)
}
$c: object(stdClass)#1 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  ["foo"]=>
  string(3) "bar"
  ["baz"]=>
  string(3) "boz"
}
$d: object(stdClass)#1 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  ["foo"]=>
  string(3) "bar"
  ["baz"]=>
  string(3) "boz"
}