用于使用预填充数据创建 stdClass 的 PHP 快速语法

标签 php oop object casting

<分区>

我应该补充说,虽然 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 json_decode and json_encode - nope; we can't call functions in the declaration of a class variable :

<?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 []'s were added in PHP 5.4, object brackets still do not exist* :

* rfc for array brackets

<?php
    class Foo {
        public $bar = {
            'foo' => 'bar',
            'bar' => 'foo'
        };
    }

    /*
        Parse error: syntax error, unexpected '{' on line 3
    */
?>

似乎唯一可行的方法是使用 __construct 并将 KVP 数组转换为对象,但将变量声明为一件事似乎完全倒退,而且在我们之前使用它,将其转换为其他东西。

__construct demo:

<?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"
        }
    */
?>

  • 是否有一些我没能找到的速记语法?
  • 如果 不是;它会被添加到 future 的 PHP 版本中吗?
  • 如果没有/直到 然后;有没有比必须添加 __construct 的每个更好的方法 单次?
  • 相反,我是否应该处理这样一个事实,即使用 在这种情况下,数组更好,尽管在我看来, 看起来更乱?

为什么?:

在为一家公司开发新的数据库类时,我不得不求助于当前代码来管理保存数据库凭据,以便稍后在代码中进行进一步检查。当然,不同的设计模式(例如 $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"
  }
}

关于用于使用预填充数据创建 stdClass 的 PHP 快速语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17951731/

相关文章:

c++ - 关于 C++ 类型和 vector

c# - 在一个类中定义 MySqlConnection 并在另一个类中使用它来处理数据库

php - 爬取页面时,如何从<a href>或<frame src>属性获取完整URL

php - 不为空不能正常工作

php - 覆盖 Laravel Spark Controller 方法

java - 如何使用 hibernate 工具生成带有注释的领域对象

尝试从双链表打印数据时 C++ 程序崩溃

php - 使用 PHP 在数据库中加载 1 行,但是

c++ - 为什么 C++ 构造函数在继承中需要默认参数?

php - 验证构造函数参数,确保参数具有正确的类型