php - 我怎样才能让两个类相互交互

标签 php

我想从另一个类中实例化一个类,但是当我尝试在类 foo 中调用 db 函数时,它会失败,除非我声明 new db() 并在同一个函数中调用该函数

class foo {
  private $db;
  public function __construct() {
    $db = new db();
// if i call $db->query(); from here it works fine
  }
  public function update(){
  $db->query();
  }
}
class db {
  public function __construct() {
  }
  public function query(){
    echo "returned";
  }
}

$new_class = new foo();
$new_class->update();

这段代码给我一个错误,说我在第 7 行有一个 undefined variable db 并调用了一个非对象上的成员函数 query()。

最佳答案

您应该使用 $this->db 而不是 $db

在你的代码中,$db__construct 函数的局部变量,

public function __construct() {
  $db = new db();
  // $db is only available within this function.
}

而你想把它放到成员变量中,所以你需要使用$this

class foo {
  private $db; // To access this, use $this->db in any function in this class

  public function __construct() {
    $this->db = new db();
    // Now you can use $this->db in any other function within foo.
    // (Except for static functions)
  }

  public function update() {
    $this->db->query();
  }
}

关于php - 我怎样才能让两个类相互交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493053/

相关文章:

php - Wamp apache 未更改 wamp 菜单中的版本

php - 在 laravel 中根据日期对配置变量进行排序

php - 在选择查询中使用选择查询?

PHP + MySQL - 搜索脚本(全文)?

php - 自定义错误页面无法直接访问

php - 未从 PHP/MySQL NuSOAP 获得响应

php - 我无法在服务器上托管我的 Laravel 应用程序?

php - 如何使用表格中的按钮删除特定行的数据?

当小数位较长时,PHP 轮次显示不正确的数字

php - 确定文件是否为 PHP 图像的最佳方法是什么?