New to Object-Oriented: Importing Variables(?)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Dusty Puppet
Forum Newbie
Posts: 1
Joined: Mon Apr 02, 2007 9:33 am

New to Object-Oriented: Importing Variables(?)

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Code: Select all

$db = new Db_Connection($config);
$login = new Db_Login($db);
(#10850)
User avatar
christian_phpbeginner
Forum Contributor
Posts: 136
Joined: Sat Jun 03, 2006 2:43 pm
Location: Java

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

Post 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 !
Post Reply