Reputation: 5818
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();
}
}
Upvotes: 2
Views: 237
Reputation: 27313
class Connection
{
private $_dbcc;
public function getConnection()
{
return $this->_dbcc;
}
public function __construct()
{
$this->_dbcc = new PDO( "mysql:host=localhost;dbname=db1;",
"root","pass1");
}
}
class Registration
{
private $_username;
private $_dbc;
public function __construct($un)
{
$this->_username = $un;
$this->_dbc = new Connection();
}
public function Fn_User_Exist()
{
$qry = "SELECT * FROM CMT_Users WHERE Username=@Username";
$result = $this->_dbc->getConnection()->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 __construct
keyword 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 like Result
because PHP is case sensitive so Result
is not equal to result
, so better to avoid typo to keep the variable name in lower case(appart when you want to do camelCase).
Upvotes: 3