【问题标题】:calling a function from php class从 php 类调用函数
【发布时间】:2016-10-25 19:00:02
【问题描述】:

我已经编写了这个 php 类,但是我在使用它时遇到了问题,

<?php
    class cs_mysql{
        protected $configPath;
        protected $db;
        function __construct($cP = null){
            $this->configPath = $cP;
            require $this->configPath;
        }
        private function connection(){
            $db = new mysqli(Config::get('dbHost'),Config::get('dbUser'),Config::get('dbPass'),Config::get('dbName'));
        }
        public function getRow($table){
            $query = 'SELECT * FROM $table ORDER BY `id` DESC';
            $sql = $this->db->query($query);
            if(!$sql){
                echo "FALSE";
            }
        }
    }
?>

我不知道如何运行数据库查询:$sql = $this-&gt;db-&gt;query($query);

【问题讨论】:

  • $this-&gt;db = new mysqli
  • 但是您是否在任何地方使用connection()?我没看到你在叫它。
  • 基于此代码,$db 将始终为空,因为 connection() 从未运行。

标签: php mysql class


【解决方案1】:

改变

$db = new mysqli(Config::get('dbHost'),Config::get('dbUser'),Config::get('dbPass'),Config::get('dbName'));

$this->db = new mysqli(Config::get('dbHost'),Config::get('dbUser'),Config::get('dbPass'),Config::get('dbName'));

$db 是类的属性。要访问类属性(和方法),您必须使用 $this 引用类实例。

【讨论】:

  • 我收到此错误:致命错误:未捕获的错误:在 /Applications/XAMPP/xamppfiles/htdocs/bonbegir/bbadmin/classes/mysql.class.php 中调用 null 上的成员函数 query() :14 堆栈跟踪:#0 /Applications/XAMPP/xamppfiles/htdocs/bonbegir/index.php(7): cs_mysql->getRow('category') #1 {main} 在 /Applications/XAMPP/xamppfiles/htdocs/ 中抛出bonbegir/bbadmin/classes/mysql.class.php 第 14 行
  • @AmirMohammadRivand 正如我在对您的问题的评论中提到的那样,您不会在任何地方致电connection(),因此$this-&gt;db 将为空。你应该先打电话给$this-&gt;connection()$this-&gt;db-&gt;query()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 2012-09-26
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
相关资源
最近更新 更多