OOP access control

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
User avatar
stakes
Forum Commoner
Posts: 48
Joined: Tue Jun 12, 2007 12:05 pm

OOP access control

Post by stakes »

Hello php-lovers!

I've run into a little problem implementing classes and accessing properties throughout them. Let me illustrate:

Code: Select all

require('../lib/class.Validate.php');
require('../lib/class.MySQL.php');

class UserProfile {
   	
			//class properties
	
			protected $db;
			
			//class construct
			
            function __construct($_POST) {
            
            $this->db = new DB(DB_HOST, DB_USER, DB_PASS, DB_NAME); 
            $validate = new Validate;
            $validate->uniqueEmail($_POST['email']);

 
            
            }
               
}
So the question is how can i access the DB object from inside the Validate object. The code inside class.Validate currently looks like this:

Code: Select all

public function uniqueEmail($input) {
	
		$input = $db->escape($email);
		$result = $db->query("SELECT * FROM user_auth WHERE email='$input'");
		
		if($result->length() == 1) {
			$_SESSION['error']['uniqueEmail'] = "Epostadressen används redan för annat konto";
		}
		
	}
Basically it just checks whether an email address is unique. So from what i've understood setting $db to PROTECTED inside the parent(?) class which is userProfile makes it accessible inside the class and it's subclasses. But right now it throws me the error:

Code: Select all

Fatal error: Call to a member function escape() on a non-object in M:\Development\base.dev\lib\class.Validate.php on line 134
And escape() is a public method inside the DB class which is as you can see initialized in the construct of UserProfile class.

Could anyone point me in the right direction on this?

thanks in advance

/Daniel
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Your Validate object could accept the database object as a parameter

Code: Select all

$validate = new Validate($db);

class Validate
{
   public function __construct($db) 
   {
      $this->db = $db;
   }

   public function uniqueEmail($email) 
   {
      $this->db->query( ... );
   }
}
Last edited by John Cartwright on Fri Dec 28, 2007 8:11 pm, edited 1 time in total.
User avatar
stakes
Forum Commoner
Posts: 48
Joined: Tue Jun 12, 2007 12:05 pm

Post by stakes »

Makes sense. Thank you Jcart. I think I'm making OOP more complex than it is :oops:
Post Reply