【问题标题】:Bads declarations of ArrayObject in PHPPHP 中 ArrayObject 的错误声明
【发布时间】:2012-06-26 20:12:55
【问题描述】:

我是 PHP 声明的新手,我不明白如何在 ArrayObject 中包含一个数组。以下代码正在运行(回显正常),但我有一些“SCREAM:忽略错误抑制”,因为“警告:在第 11 行从空值创建默认对象”和“警告:从空值创建默认对象” ...在第 13 行"

我愿意:

$model = new stdClass();
$model->name = new stdClass();
$model->image = new ArrayObject();
$model->image->url = new stdClass();
$model->image->copyright = new stdClass();
$model->image->total = new stdClass();

$model->name = "France";
echo "Name : ".$model->name."<hr/>";
$model->image[0]->url = "/model1.jpg";
$model->image[0]->copyright = "Bellami";
$model->image[1]->url = "/model2.jpg";
$model->image[1]->copyright = "Bellami";
$model->image->total=2;

echo "Image 1 : ".$model->image[0]->copyright." - ".$model->image[0]->url."<hr/>";
echo "Image 2 : ".$model->image[1]->copyright." - ".$model->image[1]->url."<hr/>";

在我的情况下必须如何声明?

【问题讨论】:

    标签: php object declaration arrayobject


    【解决方案1】:

    这对我有用,但我怀疑有更好的方法:

    $model = new stdClass();
    $model->name = new stdClass();
    $model->image = new ArrayObject();
    $model->image->offsetSet( 0, new ArrayObject());
    $model->image->offsetSet( 1, new ArrayObject());
    
    $model->name = "France";
    echo "Name : ".$model->name."<hr/>";
    $model->image[0]->offsetSet( 'url', "/model1.jpg");
    $model->image[0]->offsetSet( 'copyright', "Bellami");
    $model->image[1]->offsetSet( 'url', "/model2.jpg");
    $model->image[1]->offsetSet( 'copyright', "Bellami");
    $model->image->total=2;
    
    echo "Image 1 : ".$model->image[0]->offsetGet('copyright')." - ".$model->image[0]->offsetGet('url')."<hr/>";
    echo "Image 2 : ".$model->image[1]->offsetGet('copyright')." - ".$model->image[1]->offsetGet('url')."<hr/>";
    

    【讨论】:

      【解决方案2】:

      为什么你需要声明对象,它是隐式定义的......这会给你自己需要的东西吗?

      $model->image[0]->url = "/model1.jpg"; 
      $model->image[0]->copyright = "Bellami"; 
      $model->image[1]->url = "/model2.jpg"; 
      $model->image[1]->copyright = "Bellami"; 
      
      var_dump($model);
      

      【讨论】:

        【解决方案3】:

        $model-&gt;image[0] 永远不会被创建,而是像对象一样被说出来。这有效:

        $model->image[0] = new ArrayObject();
        $model->image[0]->url = "/model1.jpg";
        $model->image[0]->copyright = "Bellami";
        $model->image[1] = new ArrayObject();
        $model->image[1]->url = "/model2.jpg";
        $model->image[1]->copyright = "Bellami";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-30
          • 2015-02-20
          • 1970-01-01
          • 1970-01-01
          • 2023-04-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多