NetBeans 8.2 PHP代码完成问题

时间:2018-01-17 00:53:04

标签: php netbeans autocomplete

因此我遇到了NetBeans代码完成问题。我目前正在尝试建立一个可以在其他文件中使用的数据库连接。在我的connection.php文件中,我可以访问所有常用的数据库方法。我的最终目标是为我的查询使用预准备语句。 enter image description here

然而,当我在register.php文件中时,顶部需要connection.php,突然代码完成不再起作用。我得到了通用弹出窗口。这是我想要实际使用这些准备语句的文件。我还想避免在每个文件中打开一个新连接。 enter image description here

所以我的问题是,是我还是NetBeans?

connection.php     

$host = "localhost";
$username = "root";
$pass = "password";
$database = "LoganWebsiteUserLogin";

try {
    $conn = new PDO('mysql:host=localhost;dbname=' . $database . ';charset=utf8mb4', $username, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected Successfully!";
} catch (PDOException $e) {
    echo "Connection failed! " . $e->getMessage();
}

register.php

<?php 
require 'connection.php';

// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];


// trying to access $conn from connection.php here, however autocomplete for 
// it is not working. NetBeans doesn't know that $conn is a PDO
$conn->

1 个答案:

答案 0 :(得分:1)

它适用于PhpStorm但不适用于Netbeans。但无论如何,不​​建议使用全局变量并导致不必要的副作用。也许尝试不同的方法。

示例:

connection.php

<?php

function db(): PDO
{
    static $pdo = null;
    if (!$pdo) {
        $host = "localhost";
        $username = "root";
        $password = "password";
        $database = "LoganWebsiteUserLogin";

        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_PERSISTENT => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
        ];
        $pdo = new PDO("mysql:host=$host;dbname=$database;charset=utf8mb4", $username, $password, $options);
    }
    return $pdo;
}

register.php

<?php

require_once __DIR__ . '/connection.php';

// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];

// Works :-)
db()->