如何避免使用include_once

In PHP, let's say I have three classes:

database.php
item.php
user.php

Both classes item and user have the statement include("database.php"); in order to connect to the database and perform queries.

Say, I have a page where I want to show user info and item info. I would have to type

include("item.php");
include("user.php");

But this, of course, gives me an error because I include the database class twice. I know I could use include_once("database.php"); in the item and user classes, but I've read read in various threads it's better not to use the _once-versions of include and require.

What is the best practice to avoid the usage of "_once" in PHP code when you need to include a database class on multiple places?

I would have thought the best solution would be not to do include calls in your main code at all. Instead, autoload your files, so they are only included when they are needed.

spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.php';
});

Now, if your code gets to something like new database(); and the database class isn't loaded, this function will include classes/database.php. If the class is used again in future, the class will already be loaded, so the autoloader won't be used again.

See the documentation for spl_autoload_register for more information.

You can include database in main script, from where other scripts are being included, however usage of include_once and require_once is normal and there is no any critical performance issue.

I am not sure about your basic fear of *_once, but ...

include("database.php");
include("item.php");
include("user.php");

One way is to call it as you need and remove the include line from the classes.