2012-04-04 137 views
0

我得到:未定义私有变量

未定义的变量:密码
未定义的变量:主机
未定义的变量:用户

我只是好奇,为什么我收到这样的通知, 虽然该变量已在类的专用部分中定义。

我不能在成员函数中使用该类的私有数据成员(因为这会打败OOP的整个概念)?

PHP文件是:

class data_base //helps handling permissins 
    { 
    private $host; 
    private $user; 
    private $password; 

    public function feed_data($hst, $usr, $pwd) 
     { 
      $host=$hst; 
      $user=$usr; 
      $password=$pwd; 
     } 
    public function get_data() 
     { 
      $info=array("host"=>" ", "user"=>" ", "password"=>" "); 
      $info['host']=$host; 
      $info['user']=$user; 
      $info['password']=$password;  
      return $info; 
     } 
     } 

    $user1=new data_base; 
    $user2=new data_base; 

    $user1->feed_data("localhost", "root", ""); //enter details for user 1 here 
    $user2->feed_data("", "", ""); //enter details for user 2 here 

    $perm_add=$user1->get_data(); 
    $perm_view=$user2->get_data(); 

回答

4

在PHP中,你必须在Java $host叫财产作为财产

$this->host; 
// instead of 
$host; 

不像例如是总是一个局部变量,因此这里未定义。

一点题外话:你可以写

$info=array("host"=>" ", "user"=>" ", "password"=>" "); 
$info['host']=$host; 
$info['user']=$user; 
$info['password']=$password;  
return $info; 

return array(
    'host'  => $this->host, 
    'user'  => $this->user, 
    'password' => $this->password 
); 

这是短期和国际海事组织更reable(无需临时变量)

+0

在这种特殊情况下,即使只是:'return get_object_vars($ this);'。 – hakre 2012-04-04 07:05:38

+0

@hakre是的。但是我对自己不喜欢,因为它可能意外暴露超过想要的,当班级延长后。我喜欢更详细的方式:) – KingCrunch 2012-04-04 07:23:19

2

在PHP中,访问实例变量,你需要使用$this->varname
只需$varname始终是该方法的局部变量。