dongsheng8158 2012-04-04 06:47
浏览 20
已采纳

未定义的私有变量

I get:

Undefined variable: password
Undefined variable: host
Undefined variable: user

I am just curious why I am getting such notices, although the variable has been defined in the private section of the class.

Can't I use private data member of the class in the member function (because that would defeat the whole concept of OOP)?

The php file is:

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();
  • 写回答

2条回答 默认 最新

  • douweihui0178 2012-04-04 06:49
    关注

    In PHP you must call a property as a property

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

    Unlike for example in java $host is always a local variable and thus undefined here.

    As a sidenote: You can write

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

    as

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

    It's short and imo more reable (No need for a temporary variable)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入