2012-12-24 25 views
0

我正在使用此PHP代碼創建具有默認單個變量的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); 


?> 

我得到這個錯誤:

enter image description here

請幫助我,如何解決它?

+1

如何使用數組來代替對象? – zerkms

+0

你沒有初始化'user1'和'user2' – Raptor

+1

@Shivan Raptor:...和'data' – zerkms

回答

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"; 
+0

「它沒有任何東西」---它實際上不是什麼,而是'NULL' – zerkms

+0

哦!它不會產生任何效果... :-( – Jooxa

+1

@ user1882503:可能對於對象來說太早了嗎?如何**陣列**? – zerkms

2

如果你想你的類靈活,你好類中$數據變量必須是一個數組。

例如:

<?php 

class Person{ 

public $data = array(); 

function __construct(){} 

} 

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

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

?> 
+2

爲什麼你需要一個空的構造函數? – zerkms

+1

它的模板從我的編輯器中,它創建一個默認的空構造函數 – Codethusiast