Creating anonymous objects in php

前端 未结 12 1883
故里飘歌
故里飘歌 2020-11-28 01:59

As we know, creating anonymous objects in JavaScript is easy, like the code below:

var object = { 
    p : \"value\", 
    p1 : [ \"john\", \"johnny\" ]
};

         


        
相关标签:
12条回答
  • 2020-11-28 02:47

    Up until recently this is how I created objects on the fly.

    $someObj = json_decode("{}");
    

    Then:

    $someObj->someProperty = someValue;
    

    But now I go with:

    $someObj = (object)[];
    

    Then like before:

    $someObj->someProperty = someValue;
    

    Of course if you already know the properties and values you can set them inside as has been mentioned:

    $someObj = (object)['prop1' => 'value1','prop2' => 'value2'];
    

    NB: I don't know which versions of PHP this works on so you would need to be mindful of that. But I think the first approach (which is also short if there are no properties to set at construction) should work for all versions that have json_encode/json_decode

    0 讨论(0)
  • 2020-11-28 02:47

    If you wish to mimic JavaScript, you can create a class Object, and thus get the same behaviour. Of course this isn't quite anonymous anymore, but it will work.

    <?php 
    class Object { 
        function __construct( ) { 
            $n = func_num_args( ) ; 
            for ( $i = 0 ; $i < $n ; $i += 2 ) { 
                $this->{func_get_arg($i)} = func_get_arg($i + 1) ; 
            } 
        } 
    } 
    
    $o = new Object( 
        'aProperty', 'value', 
        'anotherProperty', array('element 1', 'element 2')) ; 
    echo $o->anotherProperty[1];
    ?>
    

    That will output element 2. This was stolen from a comment on PHP: Classes and Objects.

    0 讨论(0)
  • 2020-11-28 02:48

    "Anonymous" is not the correct terminology when talking about objects. It would be better to say "object of anonymous type", but this does not apply to PHP.

    All objects in PHP have a class. The "default" class is stdClass, and you can create objects of it this way:

    $obj = new stdClass;
    $obj->aProperty = 'value';
    

    You can also take advantage of casting an array to an object for a more convenient syntax:

    $obj = (object)array('aProperty' => 'value');
    print_r($obj);
    

    However, be advised that casting an array to an object is likely to yield "interesting" results for those array keys that are not valid PHP variable names -- for example, here's an answer of mine that shows what happens when keys begin with digits.

    0 讨论(0)
  • 2020-11-28 02:56

    Yes, it is possible! Using this simple PHP Anonymous Object class. How it works:

    // define by passing in constructor
    $anonim_obj = new AnObj(array(
        "foo" => function() { echo "foo"; }, 
        "bar" => function($bar) { echo $bar; } 
    ));
    
    $anonim_obj->foo(); // prints "foo"
    $anonim_obj->bar("hello, world"); // prints "hello, world"
    
    // define at runtime
    $anonim_obj->zoo = function() { echo "zoo"; };
    $anonim_obj->zoo(); // prints "zoo"
    
    // mimic self 
    $anonim_obj->prop = "abc";
    $anonim_obj->propMethod = function() use($anonim_obj) {
        echo $anonim_obj->prop; 
    };
    $anonim_obj->propMethod(); // prints "abc"
    

    Of course this object is an instance of AnObj class, so it is not really anonymous, but it makes possible to define methods on the fly, like JavaScript do.

    0 讨论(0)
  • 2020-11-28 02:56

    Can this same technique be applied in case of PHP?

    No - because javascript uses prototypes/direct declaration of objects - in PHP (and many other OO languages) an object can only be created from a class.

    So the question becomes - can you create an anonymous class.

    Again the answer is no - how would you instantiate the class without being able to reference it?

    0 讨论(0)
  • 2020-11-28 03:00

    From the PHP documentation, few more examples:

    <?php
    
    $obj1 = new \stdClass; // Instantiate stdClass object
    $obj2 = new class{}; // Instantiate anonymous class
    $obj3 = (object)[]; // Cast empty array to object
    
    var_dump($obj1); // object(stdClass)#1 (0) {}
    var_dump($obj2); // object(class@anonymous)#2 (0) {}
    var_dump($obj3); // object(stdClass)#3 (0) {}
    
    ?>
    

    $obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:

    <?php
    
    echo json_encode([
        new \stdClass,
        new class{},
        (object)[],
    ]);
    
    ?>
    

    Outputs:

    [{},{},{}]
    

    https://www.php.net/manual/en/language.types.object.php

    0 讨论(0)
提交回复
热议问题