【问题标题】:PHP5.4+ Is there an alternative to explicitly creating dozens of objects to avoid warning?PHP5.4+ 是否有替代显式创建数十个对象以避免警告的替代方法?
【发布时间】:2014-09-24 13:20:06
【问题描述】:

从 PHP5.4 开始,当您尝试使用隐式转换作为对象时,PHP 会抛出警告。

消息:从空值创建默认对象

通常,这可以通过显式声明变量类型来防止 - 例如

$thing = new stdClass();

但是当您开始处理将对象转换为 XML 的库时,这会变得非常烦人。所以你之前的代码说

$xml->authentication->identity->accountID->username = "myName";

变得臃肿

$xml = new stdClass();
$xml->authentication = new StdClass();
$xml->authentication->identity = new stdClass();
$xml->authentication->identity->accountID = new stdClass();
$xml->authentication->identity->accountID->username = new stdClass();
$xml->authentication->identity->accountID->username = "myName";

但在像使用 XML 这样的实例中,像这样的深节点树非常常见。

有没有一种替代方法可以以这种方式显式声明每个节点的每个级别,而不通过禁用警告来伪造它?

【问题讨论】:

    标签: php stdclass


    【解决方案1】:

    这个怎么样:

    class DefaultObject
    {
        function __get($key) {
            return $this->$key = new DefaultObject();
        }
    }
    

    然后:

    $xml = new DefaultObject();
    $xml->authentication->identity->accountID->username = "myName"; // no warnings
    

    【讨论】:

      【解决方案2】:

      试试这个:

      <?php
      class ArrayTree
      {
          private $nodes = array();
      
          public function __construct() {
          }
      
          public function __get($name) {
              if( !array_key_exists($name, $this->nodes) ) {
                  $node = new ArrayTree();
                  $this->nodes[$name] = $node;
                  return $node;
              }
              return $this->nodes[$name];
          }
      
          public function __set($name, $value) {
              $this->nodes[$name] = $value;
          }
      
          // ...
      }
      
      $xml = new ArrayTree;
      $xml->authentication->identity->accountID->username = 'myName';
      
      var_dump($xml->authentication->identity->accountID->username);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多