drws65968272 2013-03-17 20:25
浏览 56
已采纳

在PHP中将属性从一种方法传递到另一种方法

I'm trying out classes and PHP:PDO. I've set up a simple class to try out some stuff but I'm getting an error "Undefined variable: conn" error.

class Cms {

    function __construct() {
        try {
            $conn = new PDO('mysql:host=localhost;dbname=blog', 'root', '');
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $error) {
            echo 'error: ' . $error->getMessage();
        }
    }

    public function read() {
        $query = $conn->query("SELECT * FROM posts");
    }
}

To my knowledge this is probably because the $conn PDO object is not being passed onto the read method because it's being set in the construct method. What is the best(proper) way to let the read method be able to use the $conn attribute?

  • 写回答

1条回答 默认 最新

  • douxie4583 2013-03-17 20:26
    关注
    class Cms {
    
        private $_conn;
    
        function __construct() {
            try {
                $this->_conn = new PDO('mysql:host=localhost;dbname=blog', 'root', '');
                $this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOException $error) {
                echo 'error: ' . $error->getMessage();
            }
        }
    
        public function read() {
            $query = $this->_conn->query("SELECT * FROM posts");
        }
    }
    

    So you create a private property, assign your PDO instance to it and use

    Some documentation: http://www.php.net/manual/en/language.oop5.properties.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题