简体   繁体   English

在类文件中使用PHP常量

[英]Using PHP constant in a class file

I am trying to build a simple script that will connect to a single database. 我正在尝试构建一个连接到单个数据库的简单脚本。 I want to putths class file onto a number of my websites and want to be able to "register" the site in my database. 我想将类文件放到我的许多网站上,并希望能够在我的数据库中“注册”该网站。

To avoid having to run SQL queries for every instantiation of the class, I wanted to "register" the domain using a PHP constant. 为了避免必须为类的每个实例化运行SQL查询,我想使用PHP常量“注册”域。

In my method I define the constant and checked it - it works, but when I check the constants in my constructor, the constant is no longer defined. 在我的方法中,我定义了常量并检查它 - 它可以工作,但是当我检查构造函数中的常量时,不再定义常量。

Here is my class file, I'm sure it's just something that I am not understanding with regards to constants. 这是我的类文件,我确定这只是我对常量不了解的东西。

 <?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();

    }
}

?>

You might try using a static class variable to hold that value. 您可以尝试使用静态类变量来保存该值。 For one, that will restrict your constant value to your class, which is a better practice than exposing the value to your entire application. 首先,这将限制您的类的常量值,这比将值暴露给整个应用程序更好。 For another, the intent of constants is that they never change and it looks like you're trying to use it as a flag. 另一方面,常量的意图是它们永远不会改变,看起来你正试图将它用作旗帜。

Constructor is the first function which is called immediately after you create an object. 构造函数是在创建对象后立即调用的第一个函数。

If you define a constant in some other function inside your class, you can't expect it to be defined in the constructor. 如果在类中的某个其他函数中定义常量,则不能指望在构造函数中定义它。 Here's why: 原因如下:

  • When you create an object - constructor is called 创建对象时 - 调用构造函数
    • Inside the constructor, you are checking if a constant is defined: of course it isn't, where did you define it? 在构造函数中,您正在检查是否定义了常量:当然不是,您在哪里定义它?
  • You are calling some function inside the class and define a constant 您正在调用类中的某个函数并定义一个常量
  • Next time when an object is created (ie page refresh) - constant is no longer defined 下次创建对象时(即页面刷新) - 不再定义常量

That's perfectly normal behavior. 这是完全正常的行为。

I think that you may not be using constants in the way that they are intended. 我认为你可能没有按照预期的方式使用常量。 Firstly, constant values cannot change during the execution of your code (hence constant). 首先,在执行代码期间,常量值不会改变(因此不变)。

We use them to assign hard coded values (only really simple values) that we can use throughout the code. 我们使用它们来分配我们可以在整个代码中使用的硬编码值(只有非常简单的值)。 The key is that you can ultimately know that they will never be different. 关键是你最终可以知道它们永远不会有所不同。

In addition to this, you do not necessarily need to know the actual value of the constant itself as you simply refer to the variable name, allowing for these values to be changed at any point without breaking your code. 除此之外,您不一定需要知道常量本身的实际值,因为您只需引用变量名称,允许在不破坏代码的情况下随时更改这些值。

Consider the following example: 请考虑以下示例:

<?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);

?>

I couldn't find any place where you call define('DOMAIN_REGISTERED', '...'); 我找不到你调用define('DOMAIN_REGISTERED', '...');地方define('DOMAIN_REGISTERED', '...'); in your code. 在你的代码中。
Anyway, as monitorjbl mentioned, consider using the static reserved word for your DB connection, so you can avoid redefinition of connections, re-registration of your domain, etc. 无论如何,正如monitorjbl所提到的,考虑为数据库连接使用static保留字,这样就可以避免重新定义连接,重新注册域名等。

It is a good thing you want to master OO programming. 想要掌握OO编程是一件好事。 One (out of many) advantages is that you can build reusable and testable code. 一个(众多)优点是您可以构建可重用且可测试的代码。

If you want to build a class that connects to a database, and that can be reused in many sites, one thing you want to avoid are dependencies . 如果您想构建一个连接到数据库的类,并且可以在许多站点中重用,那么您要避免的一件事就是依赖项 A dependency on a constant or another class makes it more difficult to reuse your code. 对常量或其他类的依赖使得重用代码变得更加困难。 Or to test and debug your code. 或者测试调试代码。

Saying that means that you want to avoid using predefined constants and pre initialized publics. 说这意味着你想避免使用预定义的常量和预先初始化的公共。

The construction of your class should look like this: 你的类的构造应如下所示:

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

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

You could use you class like this: 你可以像这样使用你的类:

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

If you want to be able to register a site to you database, write a Register method: 如果您希望能够将站点注册到您的数据库,请编写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
   }
}

And use it like this: 并像这样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM