Creating anonymous objects in php

前端 未结 12 1956
故里飘歌
故里飘歌 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: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.

提交回复
热议问题