2
In PHP when I do a Singleton is created an instance for each request that tries to open a connection to the database or instantiating a single time she "always" will stay in memory for all requests?
example:
class Connect{
private static $conn;//qual o escopo dessa variavel?
/**
* Padrão singleton
*/
public static function getConnection(){
if(self::$conn==NULL){
//vai entrar aqui toda vez que uma requisição do usuario tenta uma comunicação com o bd?
self::$conn= new PDO(...);
}
return self::$conn;
}
I don’t know much about php, but something tells me that the code is wrong, like the private variable and static. I think the variable should be private only and the yes method should be static. Please correct me if I’m wrong.
– Rubico
It’s not wrong. Singleton is just like that in PHP. You need a static variable (because it is static, rsrs), and so the instance will remain active inside. Then, if it is null (which will only happen once), it instantiates
PDO
. If not, it returns the connection already instantiated. There is nothing wrong (with the code, I don’t mean the use of Pattern)– Wallace Maxters
@Rubico There is no way to access an instance member using the static method. Which instance would you be talking about? Actually there are cases in the pattern that do the opposite and there are instance methods (not all) that access static members (normal since there is only one).
– Maniero
Forget it, guys, I was full of shit. Just as @Wallacemaxters said, it should be static, otherwise its state would be preserved by the instance and not by the class.
– Rubico