用于创建带有预填充数据的stdClass的PHP快速语法
参见英文答案 >
declare property as object?????????????????????????????????????4个
我应该说,虽然KVP阵列工作正常,但我喜欢做OOP时的对象,因为$foo-> bar-> foo在我看来似乎比$foo-> bar [‘foo’]更清晰. PHP有一种很好的方法可以通过$foo = array(‘foo’=>’bar’)创建带有预先填充数据的数组;甚至是new 5.4 bracket syntax:$foo = [‘foo’=> ‘bar’],但对象(stdClass)似乎没有相同的语法. Array demo: <?php class Foo { public $bar = array( 'foo' => 'bar','bar' => 'foo' ); } $foo = new Foo; var_dump($foo->bar); /* array(2) { ["foo"]=> string(3) "bar" ["bar"]=> string(3) "foo" } */ ?> 太棒了 – 如果我们想在不使用__construct的情况下对对象做同样的事情呢? Try #1 – casting to object – nope; we can’t cast in the declaration of a class variable: <?php class Foo { public $bar = (object)array( 'foo' => 'bar','bar' => 'foo' ); } /* Parse error: syntax error,unexpected T_OBJECT_CAST on line 4 */ ?> Try #2 – using <?php class Foo { public $bar = json_decode(json_encode(array( 'foo' => 'bar','bar' => 'foo' ))); } /* Parse error: syntax error,unexpected '(',expecting ',' or ';' on line 3 */ ?> Try #3 – using javascript style brackets – nope; even though * rfc for array brackets <?php class Foo { public $bar = { 'foo' => 'bar','bar' => 'foo' }; } /* Parse error: syntax error,unexpected '{' on line 3 */ ?> 似乎工作的唯一方法是使用__construct并将KVP数组转换为对象,但是将变量声明为一件事似乎完全倒退,在我们使用它之前,将其转换为其他内容.
<?php class Foo { public $bar = array( 'foo' => 'bar','bar' => 'foo' ); public function __construct() { $this->bar = (object)$this->bar; } } $foo = new Foo; var_dump($foo->bar); /* object(stdClass)#2 (2) { ["foo"]=> string(3) "bar" ["bar"]=> string(3) "foo" } */ ?> >是否有一些我无法找到的简写语法? 为什么?: 在公司的新数据库类上工作时,我不得不求助于当前代码,以便管理保存数据库凭据,以便稍后在代码中进一步检查.当然,不同的设计模式,例如$connectionHost,$connectionDatabase等也可以正常工作 – 但它似乎对我来说很混乱. Example: <?php class DB { public $connection = array( 'host' => null,'database' => null,'user' => null,'engine' => null ); public function __construct($host,$database,$user,$engine = 'mysql') { //Essentially I'd like the following line not to be needed: $this->connection = (object)$this->connection; $this->connection->host = $host; $this->connection->database = $database; $this->connection->user = $user; $this->connection->engine = $engine; } } $db = new DB('127.0.0.1','server_db','my_user'); var_dump($db->connection->host); ?> http://codepad.org/vwy1y9NP 解决方法
是的,坚持一个阵列.没有简单的方法来声明对象.但是,如果您必须,可以直接分配嵌套属性,而无需自己实例化中间对象:
php > $x = new StdClass; php > $x->foo->bar = 'baz'; php > var_dump($x); object(stdClass)#2 (1) { ["foo"]=> object(stdClass)#1 (1) { ["bar"]=> string(3) "baz" } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |