如何在php中使用变量作为DEFINE值

时间:2016-02-11 12:58:19

标签: php constants

当我将值硬编码为常量时

define("SERVER","localhost");
 define("USER","root");
 define("PASSWORD","mypass");
 define("DATABASE","my_db");
 define("PORT","3306");

但我必须从变量中获取价值,但这不起作用:

define("SERVER",$host);
 define("USER",$username);
 define("PASSWORD",$password);
 define("DATABASE",$database);
 define("PORT","3306");


$conn = new connection(SERVER,USER,PASSWORD,DATABASE,PORT);
  

我在线搜索,即使是PHP手册也没有显示常量的例子   变量的值。对于我的应用程序,我必须从变量,如何获得它   为了做到这一点?

我收到的错误是这样的:

Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\wamp\www\ezy\class.dbconnect.php on line 33

config.php的完整代码

<?php
session_start();
//read for config details  
$myFile = "details.txt";
$lines = file($myFile);

$host = $lines[0];//localhost
$username = $lines[1];//root
$password = $lines[2];//mypass
$org_name = $lines[3];//zealous
$database = $lines[4];//zealous_db

//include files starts
include('class.dbconnect.php');
//include files ends

//db credentials localhost

 define("SERVER",$host);
 define("USER",$username);
 define("PASSWORD",$password);
 define("DATABASE",$database);
 define("PORT","3306");

 $conn = new connection(SERVER,USER,PASSWORD,DATABASE,PORT);

?>

类dbconnect.php

<?php
interface db
{
    public function __construct($param,$param2,$param3,$param4,$param5);
}
abstract class connectionStatus
{
    public function connectionStatus()
    {
        echo "Connection Established!";
    }
}
class connection extends connectionStatus implements db 
{
    public static $server;
    public static $user;
    public static $pass;
    public static $dbname;
    public static $port;    
    public static $pdo;


    public  function __construct($param,$param2,$param3,$param4,$param5)
    {
      self::$server = $param;
      self::$user = $param2;
      self::$pass = $param3;
      self::$dbname = $param4;
      self::$port = $param5;

      try 
      {
          self::$pdo = new PDO('mysql:host='.self::$server.'; dbname='.self::$dbname, self::$user, self::$pass);
          self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      } catch(PDOException $e)
      {
          echo 'ERROR: ' . $e->getMessage();
      }

      self::$pdo->query("use ".self::$dbname);
      //$this->connectionStatus();

    }
}

?>

1 个答案:

答案 0 :(得分:3)

为什么你需要创建define为什么不做

<?php
session_start();

//read for config details  
$lines = file("details.txt");

include('class.dbconnect.php');

$conn = new connection(trim($lines[0]),
                       trim($lines[1]),
                       trim($lines[2]),
                       trim($lines[4]),
                       '3306'
                      );
?>

我不是说它是一个好主意,但是在没有必要时创建DEFINE()的重点是什么

就我个人而言,我很想将你从文件中获取的所有这些值作为私有属性添加到class.dbconnect.php类。将它们保存在文本文件中就像将它们保存在.php文件中一样。 至少.php个文件会自动受到Web服务器的保护,除非您执行某些操作以使其受到保护,否则.txt文件不会被保护