2012-09-17 66 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

你是对的,但我有点快;) –