0

我是 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/>";

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

4

3 回答 3

0

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

$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/>";
于 2012-06-26T20:20:39.880 回答
0

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

$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);
于 2012-06-26T20:24:24.777 回答
0

$model->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";
于 2012-06-26T20:33:57.187 回答