Here I asked this question, where and how is it better to use static methods?

For example, there is a class for working with the database, and the class has a query method.

$db = new Db(); $db->query($sql); 

If you use here not a class object, but a statistical method to do, how best?

For convenience, I better use static, but how to use it correctly, and will it not be worse ...?

 Db::query($sql); 
  • 3
    static method - a method not tied to an object instance, imagine a method returning the same answer from a class or instance, that is, not tied to the instance data, so is it worth adding it to the instance? - Jean-Claude
  • That is, if the method does not use the attributes of its class, then it is safe to use it? .. I thought there is some connection with static properties, as if the expression cannot be used (up to 5.6 but also there are restrictions) ъ - user190134
  • and it’s not easier not to think, but to try, I’m not talking about reading the documentation or books for teapots. - Jean-Claude
  • one
    I read the material on different sites, and use. Everything works, but thought correctly l - user190134
  • one
    Static method = function + namespace - Ninazu

1 answer 1

Your example with DB is incomplete, so you have doubts. The key point here is where you will get the connection to the database. If you have them sewn into the class is wrong. If they are rendered to the cofig, this is better, and there is a logic for accessing the configuration and getting the parameters inside your Db class, but you need to think about the situation when you have several connections, then either send the connection ID using which the parameters from the config will be received. But this makes your class dependent on this config.

 Db::connect('mainDb')->query($sql)->fetchAll(); 

And the third option is when you transfer the connection parameters to the constructor, but you need to think about how to forward this instance to all other modules so that you can reach the base. Do not use $ db as a global variable. You can of course create a certain $ application that will store all the components and transfer it to all modules. But I do not like this approach. Personally, I used statics for the top level, and it already has components in the form of instances. Like the way it is done in Yii2 through Piping

 Yii::$app->db->query($sql)->fetchAll();