what is the difference if I return and don't return?
If you capture the returned value but don't return it, the difference is that you'll get null
instead of \PDO
:
class Database
{
private $conn;
public function Connect($host, $dbname, $user, $pass)
{
$this->conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
}
$database = new Database();
$connection = $database->Connect('localhost', 'test', 'test', 'test');
var_dump($connection); // NULL
If you don't capture it, there's no difference (aside from the potential of being able to catch the value in the future).
Additionally, since objects are passed by reference (rather than value) capturing the value has two side effects:
You have direct uncontrolled access to a private property:
$database = new Database();
$connection = $database->Connect('localhost', 'test', 'test', 'test');
$connection->rollBack(); // Why not?
You might be able to use the method to obtain two different connections from the same instance (something the class is not designed to handle):
$database = new Database();
$connection1 = $database->Connect('localhost', 'test', 'test', 'test');
$connection2 = $database->Connect('localhost', 'test', 'test', 'test');
var_dump($connection1, $connection2);
object(PDO)#2 (0) {
}
object(PDO)#3 (0) {
}
In short, it's a pretty pointless confusing head-scratching design. I don't know what features you have in mind with this class but this doesn't seem to be the way.