Page 1 of 1

OOP access control

Posted: Fri Dec 28, 2007 7:39 pm
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

Posted: Fri Dec 28, 2007 7:54 pm
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( ... );
   }
}

Posted: Fri Dec 28, 2007 8:05 pm
by stakes
Makes sense. Thank you Jcart. I think I'm making OOP more complex than it is :oops: