Undefined private variables

Go To StackoverFlow.com


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)
    public function get_data()
            $info=array("host"=>" ", "user"=>" ", "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

2012-04-04 06:47
by Saket


In PHP you must call a property as a property

// instead of

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"=>" ");
return $info;


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

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

2012-04-04 06:49
by KingCrunch
In that particular case even just: return get_object_vars($this); - hakre 2012-04-04 07:05
@hakre Yes. But I for myself don't like it, because it may accidentally expose more than wanted, when the class gets extended later. I like the more verbose way : - KingCrunch 2012-04-04 07:23


In PHP, to access instance variables, you need to use $this->varname.
Just $varname is always a variable local to the method.

2012-04-04 06:49
by deceze