PHP define() doesn't seem to be working with i

2019-06-15 23:26发布

问题:

I've been trying my hand at OO PHP, and currently have three files. I have a class_lib.php which, at the moment, just has a databaseServer class, an index.php file and a definitions.php file. I want to put all my sensitive database info into the definitions file. However, when I do, I get an error when trying to connect to the database: "Unkown server DB_HOST". My definitions file is:

<?php
define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PASS","password");
define("DB_NAME","database");
?>

Then I use them in the index file like so:

include('definitions.php');
include('class_lib.php');

$testing = new databaseServer();

$testing->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);

And the function I use in the databaseServer class is this:

    function connect($host,$user,$pw,$db) {
        $this->con = mysql_connect($host,$user,$pw);
        if (!$this->con) {
            die('Could not connect: ' . mysql_error());
            }
        $this->selectDb($db);
        }

    function selectDb($database) {
        $this->db = mysql_select_db($database,$this->con);
        if (!$this->db) {
            echo "Could not Select database: " . mysql_error();
            }
        }

Any ideas why this would not work? I've also tried putting the definitions file into an include in the class_lib file, but it still doesn't work.

回答1:

This should work fine, and I've never seen it not work.

  • Make 100% sure the includes are in the correct order (the defines need to be loaded first)

  • Make test outputs of the constant values in the "definitions.php" file and the index file

  • Make 100% sure you are calling the right files



回答2:

Please check if your server supports short_open_tag this value would be commented. I just enabled it with on and it started working.



回答3:

working

<?php
define('KLINGON_SEPARATOR', '');
?>

not working

<?php
define('KLINGON_SEPARATOR', '');

silly... IDEA says "redundant closing tag"



回答4:

call it config.php

if(!$link)
{

die('Failed to connect to server: ' . mysql_error());

}

$db = mysql_select_db(DB_DATABASE);
if(!$db)
{

die("Unable to select database");

}

?>

then include("config.php"); on your pages



回答5:

You just need to take out the define functions of the destinations file and transfer it to the source file (in your case "translation.php") and ready to work!

Like this the bug with define functions on receiving string params do not happen and you will include the CONSTANTS implemented already.

I faced this trouble and found myself just this one solution.



回答6:

The key in this is using the constant() function to pull the value from the defined constants:

echo constant("DB_USERNAME");