Page 1 of 1

New to Object-Oriented: Importing Variables(?)

Posted: Mon Apr 02, 2007 9:46 am
by Dusty Puppet
Hi gang,

I'm trying to give myself a quick introduction to Object-Oriented PHP. I'd always assumed you could call variables from inside classes without any problems...but it seems I'm wrong. Here's the problem.

I call (via require_once) my db_login.php file, and I also call (via require_once) connectionclass.php.

In connectionclass.php, I'm trying to access a variable from db_login.php ($db_username to be precise)...and it just won't recognise anything inside the class.

Echoing $db_username returns the correct variable if I echo it before the class is declared, but if I try to echo it from within the constructor function, it returns nothing. var_dump returns "NULL".

Apologies for what I suspect is quite a newbie-ish question, but if anyone can help out I'd be really appreciative.

Cheers,
- Dusty Puppet

Posted: Mon Apr 02, 2007 9:50 am
by feyd
Class scope is completely different than global scope. Pass the information into the class during creation or connection generation. The "global" keyword is not a substitute.

Posted: Mon Apr 02, 2007 12:24 pm
by Christopher

Code: Select all

$db = new Db_Connection($config);
$login = new Db_Login($db);

Re: New to Object-Oriented: Importing Variables(?)

Posted: Tue Apr 03, 2007 2:40 pm
by christian_phpbeginner
Dusty Puppet wrote: In connectionclass.php, I'm trying to access a variable from db_login.php ($db_username to be precise)...and it just won't recognise anything inside the class.
Let us know how did you access the variable ?? Does the variable STATIC,PRIVATE,PUBLIC, or PROTECTED ???

Maybe you should add a GETTER and SETTER method in your db_login.php.

Code: Select all

<?php
   class db_login {
      private $_dbUsername;
      
      public function getUsername() {
         return $this->_dbUsername();
      }
      
      public function setUsername($username) {
         $this->_dbUsername = $username;
      }
   }
?>
then, somewhere in your connectionclass.php file:

Code: Select all

<?php
   class connectionclass {
      private $_username;
      
      public function __construct(db_login $dbLogin) {
         $this->_username = $dbLogin->getUsername();         
      }
   }
?>
Of course this is just a very simple example, and it still could be improved !