I am creating 2 Class and from 1 class I am referring the other class a PDO Object. But when I refer any string of that class, but not when PDO Object. Any ideas?
Here is my code
class Connection
{
private $dbcc;
public function Fn_Db_Conn()
{
$this->dbcc = new PDO( "mysql:host=localhost;dbname=db1;",
"root","pass1");
return $this->dbcc;
}
}
class Registration
{
private $Username;
private $dbc;
public function Registration($Un)
{
$this->Username = $Un;
$this->dbc = new Connection;
$this->dbc->Fn_Db_Conn();
}
public function Fn_User_Exist()
{
$Qry = "SELECT * FROM CMT_Users WHERE Username=@Username";
$Result = $this->dbc->prepare($Qry);
$Result->bindParam("@Username",$this->Username);
$Result->execute();
print $Result->rowCount();
}
}
I have also modified the Connection class to create the PDO object in the constructor and added a getConnection method for accessing the PDO object.
You should use the
__constructkeyword for constructor, naming the constructor as the class name is the old syntax and make the code more difficult to edit.Last point, it depends on people but I prefer to prepend protected and private properties or methods by an underscore
_, this way we can identify easily if the method/property is accessible outside of the class or not. You should aboid using variable likeResultbecause PHP is case sensitive soResultis not equal toresult, so better to avoid typo to keep the variable name in lower case(appart when you want to do camelCase).