如何将类外部的$connection变量传入PHP类内函数?
解决PHP中「Undefined variable: connection」错误
错误根源
你已经明确问题:全局变量$connection无法在article类的方法内部直接访问,导致第38行调用$connection->prepare()时报错。下面提供两种可行的实现方式,将连接对象传入类方法。
方式一:通过构造函数注入连接对象(推荐)
将数据库连接对象在实例化类时传入,保存为类的属性,这样类中所有需要使用连接的方法都能直接调用。
修改后的完整代码:
<?php require('connection.php'); $instance = new database(); $connection = $instance->connection(); class article{ // 定义私有属性存储数据库连接 private $dbConnection; // 构造函数,接收外部传入的连接对象 public function __construct($connection){ $this->dbConnection = $connection; } public function poll(){ $test = isset($_GET['page']) ? $_GET['page'] : ''; if ($test =='add_article') { $this->add_articles(); } elseif ($test=='my_articles') { $this->my_articles(); } return; } public function my_articles(){ include ("my_articles.php"); } public function add_articles(){ require("add_article.php"); $username = isset($_POST['username']) ? $_POST['username'] : ''; $amount = isset($_POST['amount']) ? $_POST['amount'] : ''; $comment = isset($_POST['comment']) ? $_POST['comment'] : ''; // 使用类属性中的连接对象 $stmt = $this->dbConnection->prepare("INSERT INTO items(item_name, amount, comment) VALUES(:username, :amount, :comment)"); $stmt->bindParam(":username",$username); $stmt->bindParam(":amount",$amount); $stmt->bindParam(":comment",$comment); $stmt->execute(); } } // 实例化类时传入连接对象 $call = new article($connection); $call->poll(); ?>
方式二:直接给目标方法传入连接参数
如果只有个别方法需要数据库连接,可以在调用方法时直接传入连接对象。
修改后的完整代码:
<?php require('connection.php'); $instance = new database(); $connection = $instance->connection(); class article{ public function poll($connection){ $test = isset($_GET['page']) ? $_GET['page'] : ''; if ($test =='add_article') { // 调用add_articles时传入连接对象 $this->add_articles($connection); } elseif ($test=='my_articles') { $this->my_articles(); } return; } public function my_articles(){ include ("my_articles.php"); } // 方法定义时添加连接参数 public function add_articles($connection){ require("add_article.php"); $username = isset($_POST['username']) ? $_POST['username'] : ''; $amount = isset($_POST['amount']) ? $_POST['amount'] : ''; $comment = isset($_POST['comment']) ? $_POST['comment'] : ''; // 使用传入的连接对象 $stmt = $connection->prepare("INSERT INTO items(item_name, amount, comment) VALUES(:username, :amount, :comment)"); $stmt->bindParam(":username",$username); $stmt->bindParam(":amount",$amount); $stmt->bindParam(":comment",$comment); $stmt->execute(); } } $call = new article(); // 调用poll时传入连接对象 $call->poll($connection); ?>
两种方式对比
- 构造函数注入:适合类中多个方法需要数据库连接的场景,一次注入全局可用,代码更简洁维护性更强。
- 方法传参:适合仅少数方法需要连接的场景,灵活性更高,避免不必要的属性占用。
内容的提问来源于stack exchange,提问作者crytowave
相关产品推荐
相关产品推荐

