Does PHP feature short hand syntax for objects?

前端 未结 7 661
囚心锁ツ
囚心锁ツ 2020-12-06 04:04

In javascript you can easily create objects and Arrays like so:

var aObject = { foo:\'bla\', bar:2 };
var anArray = [\'foo\', \'bar\', 2];

7条回答
  •  臣服心动
    2020-12-06 04:19

    The method provided by crescentfresh works very well but I had a problem appending more properties to the object. to get around this problem I implemented the spl ArrayObject.

    class ObjectParameter extends ArrayObject  {
         public function  __set($name,  $value) {
            $this->$name = $value;
        }
    
        public function  __get($name) {
          return $this[$name];
        }
    }
    
    //creating a new Array object
    $objParam = new ObjectParameter;
    //adding properties
    $objParam->strName = "foo";
    //print name
    printf($objParam->strName);
    //add another property
    $objParam->strUser = "bar";
    

    There is a lot you can do with this approach to make it easy for you to create objects even from arrays, hope this helps .

提交回复
热议问题