вторник, февраля 10, 2009

PHP Array and Object Magic

Sometimes it will be useful to convert object to array or array to object: iterate, store, modify, etc.

It's simple with PHP5:
$myItem = array(
    "color" => "black",
    "size" => "medium",
    "pieces" => 100,
    "cost" => 44.99
);

$myItemObject = (object) $myItem;

echo "Array as object:\n";
print_r($myItemObject);
echo "\n";

$myItemArray = (array) $myItemObject;
echo "Object as array:\n";
print_r($myItemArray);

Output:
Array as object:
stdClass Object
(
[color] => black
[size] => medium
[pieces] => 100
[cost] => 44.99
)

Object as array:
Array
(
[color] => black
[size] => medium
[pieces] => 100
[cost] => 44.99
)

Be careful with protected and private class members:
class Casting
{
    public $pub = "I'm a public member";
    protected $pro = "I'm a protected from outlanders";
    private $pri = "I'm a hidden property";
}

$casting = new Casting();

print_r($casting);
print_r((array) $casting);

Output:
Casting Object
(
[pub] => I'm a public member
[pro:protected] => I'm a protected from outlanders
[pri:private] => I'm a hidden property
)
Array
(
[pub] => I'm a public member
[*pro] => I'm a protected from outlanders
[Castingpri] => I'm a hidden property
)