0

我正在使用这个 PHP 代码来创建带有默认单变量的 PHP 类。但这并不完美。

Note:我需要将数据存储在单个变量中。

<?PHP

class hello
{
    public $data;
}

$test = new hello();

$test->data->user1->name = "Charan";
$test->data->user1->sex  = "male";
$test->data->user1->age  = "25";

$test->data->user2->name = "Kajal";
$test->data->user2->sex  = "female";
$test->data->user2->age  = "21";


print_r($test->data->user1);


?>

我收到了这个错误:

在此处输入图像描述

请帮助我,如何解决?

4

2 回答 2

4

您只声明了变量,但尚未将其设置为“类型”。例如,您试图将值分配给对象的属性......但$data不是对象 - 它不是任何东西。您需要$data在类的构造函数中分配一个对象,或者从类外部分配它。

构造函数

class hello
{
    public $data;

    public function __construct() {
        $this->data = new StdClass();

        // assuming you want the users set up here as well
        $this->data->user1 = new StdClass();
        $this->data->user2 = new StdClass();
    }
}

从外面:

// assume we are use the same class definition from your orginal example
$test = new hello();
$test->data = new StdClass();
$test->data->user1 = new StdClass();
$test->data->user2 = new StdClass();

$test->data->user1->name = "Charan";
$test->data->user1->sex  = "male";
$test->data->user1->age  = "25";

$test->data->user2->name = "Kajal";
$test->data->user2->sex  = "female";
$test->data->user2->age  = "21";
于 2012-12-24T08:31:54.010 回答
2

如果你想让你的类灵活,你好类中的 $data 变量必须是一个数组。

例如:

<?php

class Person{

public $data = array();

function __construct(){}

}

$person = new Person();
$person->data['name'] = 'Juan Dela Cruz';

echo $person->data['name'];

?>
于 2012-12-24T08:35:18.807 回答