Home > Backend Development > PHP Tutorial > How to Properly Access External Variables (like a Database Object) within a PHP Class?

How to Properly Access External Variables (like a Database Object) within a PHP Class?

DDD
Release: 2024-12-07 03:08:14
Original
987 people have browsed it

How to Properly Access External Variables (like a Database Object) within a PHP Class?

Using Global Variables in a Class

You are attempting to create a pagination class that utilizes an external variable. However, you are encountering an error: "Call to a member function query() on a non-object."

The issue arises because the external variable, $db, is not directly accessible within the class. To resolve this, we will explore two main approaches:

Approach 1: Dependency Injection

Dependency injection involves passing the database object as an argument to the class's constructor. This method ensures that the class has access to the necessary dependency.

class Paginator
{
    protected $db;

    public function __construct(DB_MySQL $db)
    {
        $this->db = $db;
    }

    public function get_records($q)
    {
        $x = $this->db->query($q);
        return $this->db->fetch($x);
    }
}
Copy after login

Approach 2: Method Injection

Alternatively, you can pass the database object as an argument to the specific method that requires it. This approach is suitable when only a few methods need access to the dependency.

class Paginator
{
    public function get_records($q, DB_MySQL $db)
    {
        $x = $db->query($q);
        return $db->fetch($x);
    }
}
Copy after login

The choice between these approaches depends on your specific requirements. Dependency injection is preferred when multiple methods require the dependency, while method injection is suitable for limited dependency usage.

The above is the detailed content of How to Properly Access External Variables (like a Database Object) within a PHP Class?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template