-3

I'm working on a project and here's what my coding practice looks like.

  • I load all the class files in config
  • I create an instance of the VITAL classes in the configuration (ie. $database = new Database()). The non-vital classes get created within the pages.
  • Inside the pages I just use $database->query to fetch data.
  • Inside functions I call global $database and take it from there.

Is this practice normal? Discouraged? Encouraged? Which method of code structure do you implement when you work on a large project?

user2103849
  • 551
  • 6
  • 17
  • 1
    I would recommend something like singletons. – Appleshell Apr 10 '13 at 19:11
  • 1
    Possible duplicate of [PHP global in functions](http://stackoverflow.com/q/5166087/1409082) and [Use global variables in a class](http://stackoverflow.com/q/11923272/1409082). – Jocelyn Apr 10 '13 at 19:14
  • sorry for asking a question, i guess everyone on here is above me – user2103849 Apr 10 '13 at 19:20
  • I don't get why this question got down-voted so heavily. I am sure that many php programmers encounter this question at some point. To answer the question in a more detailed manner: You could use a [static class][1] or a [singleton][2] to avoid juggling with globals. [1]: http://de1.php.net/manual/en/language.oop5.static.php [2]: http://php.net/manual/de/language.oop5.patterns.php – Appleshell Apr 11 '13 at 07:07

2 Answers2

1

Do not initiate classes you may not use, only these you will use for sure. For other use autoloading feature.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
-2

If you make your methods static, you don't need to pass a reference around.

class Database {
    static function query($...) {...}
    ...
}

You probably still want the constructor to initiate the connection, but once that's done you can simply call Database::query(...).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Apparently this is called a Singleton class. I did not know that until I read Adam's comment on the question XD – Niet the Dark Absol Apr 10 '13 at 19:13
  • the database class creates a new MySQLi object.. i don't want to create the object and connect that each time i want to execute a query. which is why i create it once, and then reuse it throughout the entire execution without actually passing the object by reference – user2103849 Apr 10 '13 at 19:16
  • That's what I tried to explain. Keep your constructor and call `new Database()` once at the start of your code, then use `Database::query()`. – Niet the Dark Absol Apr 10 '13 at 19:17