如何使用 PHP 将其他 class 对象调用到另一个 class 函数

how to call other class object to another class fnction using PHP

我正在处理一期。我需要使用 PHP 将一个 class 对象传递给另一个 class 函数。我在下面解释我的代码。

db.php:

class DBOperations{
    // constructor
    private $conn;
    function __construct() {
        $this->connect();
    }
    // destructor
    function __destruct() {
        // $this->close();
    }
    public function prepare_param(){
        echo 'test';
    }
}
$dbo = new DBOperations();

newclass.php:

require_once('db.php');
class DBhandler
{

    function __construct()
    {

    }
    function __destruct() {
        // $this->close();
    }
    public function select_all_profile(){
        $output=$dbo->prepare_param();
    }
}
$dbh = new DBhandler();
print_r($dbh->select_all_profile());exit;

这里我需要将DBOperations对象(i.e-$dbo)传递给DBhandlerclass函数来执行第一个class函数,它不是发生。请帮我解决这个问题。

Require_once 存储变量时在重复函数中可能无法正常工作。

为确保变量 bar 在每次函数调用时可用,将 require 替换为 require 一次。例如情况:

经过尝试和测试。

1st:第一个 class 中的行 $this->connect(); 会出错。

<?php
class DBOperations{
    // constructor
    private $conn;
    function __construct() {
        //$this->connect();  // I have commented it out.
    }
    // destructor
    function __destruct() {
        // $this->close();
    }
    public function prepare_param(){
        echo 'test';
    }
}
$dbo = new DBOperations();

class DBhandler
{

    function __construct()
    {

    }
    function __destruct() {
        // $this->close();
    }
    public function select_all_profile($dbo){
        $output=$dbo->prepare_param();
    }
}
$dbh = new DBhandler();
print_r($dbh->select_all_profile($dbo));exit;  // This will print 'test'
?>

您遗漏了变量作用域问题。您在 db.php 中实例化 DBOperations(),但此变量在另一个文件的 class 中将不可用。

你真的应该做更好的实例化,而不仅仅是在文件中,但是要解决你的问题,请将 DBOperations 对象传递到 DBhandler().

db.php:

class DBOperations{

    private $conn;

    function __construct() {
        $this->connect();
    }

    public function prepare_param(){
        echo 'test';
    }
}
$dbo = new DBOperations();

newclass.php:

require_once('db.php');

class DBhandler
{
    private $dbo;

    function __construct(DBOperations $dbo)
    {
        $this->dbo = $dbo;
    }

    public function select_all_profile(){
        $output = $this->dbo->prepare_param();
    }
}
$dbh = new DBhandler($dbo);
print_r($dbh->select_all_profile());exit;

一个常见的结构是将 DBOperations 值传递给 DBhandler class 的构造函数,因为它可以重复使用多次。这通常称为依赖注入 (DI),用于使用任何依赖项配置 classes,而不是在每个 class.

中创建它们
require_once('db.php');
class DBhandler
{
    private $dbo;
    function __construct( $dbo )
    {
        $this->dbo = $dbo;
    }
    function __destruct() {
        // $this->close();
    }
    public function select_all_profile(){
        $output=$this->dbo->prepare_param();
    }
}
$dbh = new DBhandler($dbo);
print_r($dbh->select_all_profile());
exit;