簡體   English   中英

在類文件中使用PHP常量

[英]Using PHP constant in a class file

我正在嘗試構建一個連接到單個數據庫的簡單腳本。 我想將類文件放到我的許多網站上,並希望能夠在我的數據庫中“注冊”該網站。

為了避免必須為類的每個實例化運行SQL查詢,我想使用PHP常量“注冊”域。

在我的方法中,我定義了常量並檢查它 - 它可以工作,但是當我檢查構造函數中的常量時,不再定義常量。

這是我的類文件,我確定這只是我對常量不了解的東西。

 <?php

/** 
 * @author bailz777
 * 
 * 
 */
class db_interface {

    public $ServerName = 'localhost:3306'; //hostname:port
    public $UserName = '******'; //mysql user
    public $Password = '******'; //mysql password
    public $DataBase = '******'; //database name
    public $Domain = 'test.com'; //Full domain name (no host)
    public $con = '';

    function __construct() {

        //on construction, we must ensure that the domain is registered in our system
        //first check if it was defined locally to avoid extra DataBase Work
        var_dump(defined('DOMAIN_REGISTERED'));
        if(!defined('DOMAIN_REGISTERED')) {
            $this->db_connect();
            $result = $this->validate_domain();
            if($result) {
                echo "<p>Domain Validated!!</p>";
            }
            $this->db_disconnect();     
        }
        else {
            echo "<p>Domain Validated!!</p>";
        }
    }

    /**
     * 
     */
    function __destruct() {

    }

    /**
     * 
     * @param unknown_type $domain
     * @return boolean
     */
    private function validate_domain() {
        $constants = get_defined_constants();
//      return $this->con;
//      print_r($constants);
var_dump(defined('DOMAIN_REGISTERED'));
        if(defined('DOMAIN_REGISTERED')) {//Check DOMAIN_REGISTERED to avoid unnecessary db work
            return TRUE;
        }
        elseif (!defined('DOMAIN_REGISTERED')) {//Check the domain is in the db
            echo '<p>Domain was not locally registered, checking DataBase</p>';
            $query = "SELECT `name` FROM `$this->DataBase`.`registered_domains` WHERE `name` = '$this->Domain'";
            $result = mysql_query($query,$this->con);
            //var_dump($result);
            if(!$result) {
                die('No result found : ' . mysql_error());
            }
            elseif (mysql_num_rows($result)==0) { //if no rows returned, then domain is not in DataBase 
                $domain_exists = FALSE;
            }
            elseif (mysql_num_rows($result)>0) { //if rows returned, then domain is in DataBase
                $domain_exists = TRUE;
                //If a domain does not exist, a mysql will be passed, use @ to suppress the error
                //The domain will be written to the db and on the next run of this function, the 
                //constant will be defined
            }
            if($domain_exists) {//If it exists Then assign CONSTANT DOMAIN_REGISTERED to TRUE
                echo '<p>Domain Found in DataBase</p>';
                echo '<p>Registering domain locally</p>';
                define("DOMAIN_REGISTERED", TRUE);
                if(DOMAIN_REGISTERED) {
                    echo '<p>Successfully registered domain locally</p>';
                }
                //var_dump(defined('DOMAIN_REGISTERED'));
                //echo DOMAIN_REGISTERED;
                return TRUE;
            }
            elseif(!$domain_exists) {//If it does not exist then add it to the registered_domains table, and assign CONSTANT __DOMAIN_TRUE__ to TRUE
                echo '<p>Domain not found in DataBase</p>';
                echo '<p>Now Registering Domain</p>';
                $query = "INSERT INTO `$this->DataBase`.`registered_domains` (`name`) VALUES ('$this->Domain')";
                $result = mysql_query($query);
                if(!$result) {
                    die('Domain not added : ' . mysql_error());
                }
                else{
                    define("DOMAIN_REGISTERED", TRUE);
                    return TRUE;
                }
            }
        }       
    }

    //Connect to mysql and define the active database
    private function db_connect() {
        $this->con = $con = mysql_connect($this->ServerName,$this->UserName,$this->Password);
        if (!$con) {
            die('Could not connect: ' . mysql_error());
        }
        else {
            echo 'Successfully connected to MySQL<br />';
            //define active database
            $this->db = mysql_select_db($this->DataBase);
            if(!$this->db) {
                die('Could not connect to Database : ' . mysql_error());
            }
            else {
                echo 'Successfully connected to DataBase<br />';
            }
        }
    }

    //disconnect from mysql
    private function db_disconnect() {
        $close =  mysql_close($this->con);
        if($close) {
            echo 'Successfully disconnected from MySQL<br />';
        }
    }

    public function add_record($fname,$lname,$email) {
        $ip = $_SERVER['REMOTE_ADDR'];
        $authorized_date = time();

    }
}

?>

您可以嘗試使用靜態類變量來保存該值。 首先,這將限制您的類的常量值,這比將值暴露給整個應用程序更好。 另一方面,常量的意圖是它們永遠不會改變,看起來你正試圖將它用作旗幟。

構造函數是在創建對象后立即調用的第一個函數。

如果在類中的某個其他函數中定義常量,則不能指望在構造函數中定義它。 原因如下:

  • 創建對象時 - 調用構造函數
    • 在構造函數中,您正在檢查是否定義了常量:當然不是,您在哪里定義它?
  • 您正在調用類中的某個函數並定義一個常量
  • 下次創建對象時(即頁面刷新) - 不再定義常量

這是完全正常的行為。

我認為你可能沒有按照預期的方式使用常量。 首先,在執行代碼期間,常量值不會改變(因此不變)。

我們使用它們來分配我們可以在整個代碼中使用的硬編碼值(只有非常簡單的值)。 關鍵是你最終可以知道它們永遠不會有所不同。

除此之外,您不一定需要知道常量本身的實際值,因為您只需引用變量名稱,允許在不破壞代碼的情況下隨時更改這些值。

請考慮以下示例:

<?php

class pizza
{
  const SIZE_SMALL  = 1;
  const SIZE_MEDIUM = 2;
  const SIZE_LARGE  = 3;

  public function getCookingTime($size)
  {
    if ($size == self::SIZE_SMALL) {
      $time = 10;
    } else if ($size == self::SIZE_MEDIUM || $size == self::SIZE_LARGE) {
      $time = 15;
    }
    return $size;
  }
}

$pizza = new pizza();
$time  = $pizza->getCookingTime(3);

// or more usefull:

$time = $pizza->getCookingTime(pizza::SIZE_SMALL);

?>

我找不到你調用define('DOMAIN_REGISTERED', '...');地方define('DOMAIN_REGISTERED', '...'); 在你的代碼中。
無論如何,正如monitorjbl所提到的,考慮為數據庫連接使用static保留字,這樣就可以避免重新定義連接,重新注冊域名等。

想要掌握OO編程是一件好事。 一個(眾多)優點是您可以構建可重用且可測試的代碼。

如果您想構建一個連接到數據庫的類,並且可以在許多站點中重用,那么您要避免的一件事就是依賴項 對常量或其他類的依賴使得重用代碼變得更加困難。 或者測試調試代碼。

說這意味着你想避免使用預定義的常量和預先初始化的公共。

你的類的構造應如下所示:

class mydb
{
   private $host;
   private $database;
   ..

   public function __construct($host, $database ..)
   {
     $this->host = $host;
     $this->database = $database;
   }
}

你可以像這樣使用你的類:

$mydb = new mydb('localhost', 'mydatabase', ..);

如果您希望能夠將站點注冊到您的數據庫,請編寫Register方法:

class mydb
{
   private $host;
   private $database;
   ..

   public function __construct($host, $database ..)
   {
     $this->host = $host;
     $this->database = $database;
   }

   public function Register( $domainname )
   {
      //connect to the database and do register stuff
   }
}

並像這樣使用它:

 $mydb = new mydb('localhost', 'mydatabase', ..);
 $mydb->Register('MyDomain');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM