【问题标题】:In PHP, how can I reach my class/public function?在 PHP 中,如何访问我的类/公共函数?
【发布时间】:2016-06-18 19:49:23
【问题描述】:

我正在使用一些 php 代码,我尝试在其中访问类/公共函数,以便在连接数据库的情况下执行 if/else 函数。我之前只使用过另一个 php 文件 (dirname(FILE) 但我不确定我应该如何调整该代码以立即到达类/公共函数,因为它们位于同一个“页面”上/php 文件。

class ConnectionInfo
{   

    public function GetConnection()
    {

    $this->conn = mysqli_connect("localhost", "user","pass", "db") or die(mysqli_error($mysql_pekare));

    }
}


$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();

if (!$connectionInfo->conn)
{
    //Connection failed

}

else
{
    //Connection succeded
}

【问题讨论】:

    标签: php


    【解决方案1】:

    一种方法是将ConnectionInfo 中的变量$conn 公开,然后在您的对象中使用它:

    class ConnectionInfo {   
        public var $conn = null;    
        public function GetConnection() {
            $this->conn = mysqli_connect("localhost", "user","pass", "db") or die(mysqli_error($mysql_pekare));
        }
    }
    

    后来:

    if (!$connectionInfo->conn) {
        //Connection failed
    }
    

    另一个是return GetConnection() 中的函数值。

    【讨论】:

    • @William.John:很高兴能提供任何帮助。
    • 顺便说一句,这种方法是否安全且没有 SQL 注入?还是只有在您使用表单时才会这样?
    • @William.John:实际上是的,因为您在这里只连接到数据库。为了防止 SQL 注入,请使用参数绑定和/或 PDO。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2011-12-23
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多