RE: object literals

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, 2009-05-01 at 17:52 +0200, Andrea Giammarchi wrote:
> you are in PHP, not in JavaScript.
> 
> In PHP arrays are like collections or hash tables.
> if you strictly need object cause
> 
> $o->stuff
> is better than
> $o['stuff']
> 
> having exactly the same number of characters, you can create a
> function like
> 
> function o(array $a){
>      $o = new stdClass;
>      foreach($a as $key => $value)
>          $o->$key = $value;
>      return $o;
> }
> 
> 
> and the syntax will be
> 
> $o = o(array(
>     'a' => "b",
>     'c' => "d"
> ));
> 
> spot the difference from (object) array(whatever) ?
> 
> I do not ... and that's why json_encode resolves associative arrays
> rather than list automatically but still, if you are in PHP, you
> should think about being familiar with associative arrays, also
> because so far is the only class you cannot create/extend.
> 
> class string {
>     // ok
> }
> 
> class object {
>     // ok
> }
> 
> class array {
>     // no way
> }
> 
> Regards

First off, you compared the syntax between creating a PHP array and a
JavaScript object when the previous post specifically spoke about
getting a PHP "OBJECT". Now you've made a rather lengthy and redundant
post trying to describe to me objects versus arrays in PHP. Lastly
you've suggested writing a function to convert an array to an object
using a foreach loop for the members which is completely unnecessary.
The following will suffice:

<?php

function o( array $a )
{
    return (object)$a;
}

?>

... and the syntax will be:

<?php

    $o = o(array
    (
        'a' => "b",
        'c' => "d",
    ));

?>

But why bother when you could have just done:

<?php

    $o = (object)array
    (
        'a' => "b",
        'c' => "d",
    );

?>

Cheers,
Rob.
-- 
http://www.interjinn.com
Application and Templating Framework for PHP


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux