class User { private $db; public function __construct($db) { $this->db = $db; } public function loadFromDB($id) { $result = $this->db->query("SELECT * FROM users WHERE id = $id"); $user = $result->fetch_assoc(); $this->name = $user['name']; $this->email = $user['email']; $this->password = $user['password']; } } // create new user object $user = new User($db); // load user data from database based on id $user->loadFromDB(1); // user data is now available to be used in the application echo $user->name; // prints user's name echo $user->email; // prints user's email
require_once 'vendor/autoload.php'; use MyPackage\DBConnection; use MyPackage\User; // create new database connection $db = new DBConnection('localhost', 'user', 'password', 'my_db'); // create new user object $user = new User($db); // load user data from database based on id $user->loadFromDB(1); // user data is now available to be used in the application echo $user->name; // prints user's name echo $user->email; // prints user's emailIn this example, loadFromDB is part of a package library (MyPackage) that includes a DBConnection class. The DBConnection class is used to establish a connection to a database, and the User class is used to manage user data. The loadFromDB method in this example is similar to the first example, but the User class is part of a larger package that includes other functionality related to database management and user authentication. This approach promotes code organization and modularity, making it easier to maintain and scale the application.