简体   繁体   中英

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.

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', '...'); 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.

It is a good thing you want to master OO programming. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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