2012-09-17 201 views
3

我的一些問題與我的PHP代碼:所有信息返回,但我無法弄清楚爲什麼我得到的錯誤。對於我的索引頁,我只包含實際使用該類的代碼行,除了某些包含的代碼外,其他代碼實際上沒有。我確定這是我建立我的__contstruct,但我不確定這樣做的適當方式。我錯過了如何從索引頁面調用它。警告:缺少參數1

這行代碼爲我的__construct工程瓦特/ o錯誤,但我不希望在我的班級分配的變量。

public function __construct(){ 
    $this->user_id = '235454'; 
    $this->user_type = 'Full Time Employee'; 


} 

這是我的課

<?php 

class User 
{ 
protected $user_id; 
protected $user_type; 
protected $name; 
public $first_name; 
public $last_name; 
public $email_address; 

public function __construct($user_id){ 
    $this->user_id = $user_id; 
    $this->user_type = 'Full Time Employee'; 


} 


public function __set($name, $value){ 
    $this->$name = $value; 

} 

public function __get($name){ 
    return $this->$name; 

} 

public function __destroy(){ 


} 


} 

?> 

這是我的索引頁我的代碼:

<?php 

ini_set('display_errors', 'On'); 
error_reporting(E_ALL); 

$employee_id = new User(2365); 
$employee_type = new User(); 

echo 'Your employee ID is ' . '"' .$employee_id->user_id. '"' . ' your employement status is a n ' . '"' .$employee_type->user_type. '"'; 

echo '<br/>'; 

?> 
+1

歡迎堆棧溢出! –

回答

10

的問題是:

$employee_type = new User(); 

構造函數需要一個參數,但是你什麼都不發送。

變化

public function __construct($user_id) { 

public function __construct($user_id = '') { 

見輸出

$employee_id = new User(2365); 
echo $employee_id->user_id; // Output: 2365 
echo $employee_id->user_type; // Output: Full Time Employee 
$employee_type = new User(); 
echo $employee_type->user_id; // Output nothing 
echo $employee_type->user_type; // Output: Full Time Employee 

如果你有一個用戶,你可以這樣做:

$employer = new User(2365); 
$employer->user_type = 'A user type'; 

echo 'Your employee ID is "' . $employer->user_id . '" your employement status is "' . $employer->user_type . '"'; 

其中輸出:

Your employee ID is "2365" your employement status is "A user type" 
+0

謝謝....這是有道理的,它的工作很好 –

+0

@MichaelCrawley歡迎您=) –

6

我不是PHP的專家,但它看起來像你創建類用戶的2個新的實例,並在第二instatiation,你是不是經過USER_ID到構造:

$employee_id = new User(2365); 

這在我看來似乎是創建一個新的User實例並將這個實例賦值給變量$ employee_id - 我不認爲這是你想要的嗎?

$employee_type = new User(); 

這看起來像你實例用戶的另一個實例,將其賦給變量$ employee_type - 但你必須調用構造函數用戶(),而不用象需要一個ID傳遞 - 因此錯誤(缺少參數)。

你的返回腳本內容看起來OK的原因是因爲User類的第一個實例有一個ID(因爲你傳入了它),而第二個實例有一個僱員類型,因爲這是在構造函數中設置的。

就像我說的,我不知道PHP,但我猜你想要的線沿線的東西更多:

$new_user = new User(2365); 
echo 'Your employee ID is ' . '"' .$new_user->user_id. '"' . ' your employement status is a n ' . '"' .$new_user->employee_type. '"'; 

在這裏,你實例分配給您的用戶類的一個實例變量$ new_user,然後訪問該單個實例的屬性。

編輯:..... Aaaaaaaaand - 我是太慢了:-)

+1

你是對的,但我有點快;) –