Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: define constants outside a class or in the constructor?

i'm new to classes and oo. I was looking for a basic MySQL class to start with, and i found "A Simple MySQL Class" by Matthew Saragusa.

These are the first lines:

define('SIMPLE_DB_SERVER', 'mysqlserver.net');
define('SIMPLE_DB_NAME', 'mydbname');
define('SIMPLE_DB_USERNAME', 'myusername');
define('SIMPLE_DB_PASSWORD', 'mypassword');
class ASimpleMySQLDB {
    public function __construct($server, $database, $username, $password){

        $this->conn = mysql_connect($server, $username, $password);
        $this->db = mysql_select_db($database,$this->conn);
    }
[...]

I wonder if there is a specific reason for which constants are defined outside the class, rather than using the constructor - example:

public function __construct(){
    $this->conn = mysql_connect('localhost', 'username', 'password');
    $this->db = mysql_select_db('database',$this->conn);
}

Or:

public function __construct($which_db){
        if($which_db=='firstdb'){
            $server='localhost';
            $username='user1';
            $password='pass1';
            $database='db1';
        }elseif($which_db=='otherdb'){
            $server='localhost';
            $username='user2';
            $password='pass2';
            $database='db2';
        }

    $this->conn = mysql_connect($server, $username, $password);
    $this->db = mysql_select_db($database,$this->conn);

}

Or using a switch or whatever.

What is the difference between the two methods? Which would you recommend? Thanks a lot :-)

like image 687
Giona Avatar asked Nov 11 '11 17:11

Giona


People also ask

How can I get constant outside class in PHP?

Class constants are useful when you need to declare some constant data (which does not change) within a class. There are two ways to access class constant: Outside the Class: The class constant is accessed by using the class name followed by the scope resolution operator (::) followed by the constant name.

Where do I put constants in PHP?

Define your constant in your top . php file, that will be included in all the other scripts. It may be your front controller, your config file, or a file created for this single purpose.

What is a correct way of defining constants in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.

How do you declare a constant in a constructor?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.


2 Answers

Though it's largely discouraged by most OO PHP developers nowadays, many libraries still employ define() to set configuration constants that will need to be modified by the end party implementing the library. These are usually stowed away in a configuration file that is required/included by the class that needs this configuration information, or is included even further back up the stack if its needed globally (Wordpress comes to mind.)

PHP 5 includes class constants to fulfill this same function but only in the scope of the class itself.

http://php.net/manual/en/language.oop5.constants.php

This approach is a good way to create class specific, unchangeable values that your library is going to need. Since one of the primary goals of employing OOP in PHP is code re-usability, this packages the configuration nicely for release. In the case of your database class, you could have const declarations before your construct method defining all the access credentials, such as the db_host, db_user and db_pass. Please note that these constants have to be accessed by ClassName::ConstName much like a static method would.

Although OOP in PHP has come a long way and is now widespread, a ton of older or more "locked in" frameworks and libraries still use the define convention, so you'll see it very commonly used even in OO environments.

like image 108
DeaconDesperado Avatar answered Sep 29 '22 08:09

DeaconDesperado


  1. So other files/classes can access the defined value (GLOBAL)
  2. Easier to edit in case you are going to change your db in future

The best way to implement this is to create a configuration file with all of this definitions. i.e

configuration.php

define('SIMPLE_DB_SERVER', 'mysqlserver.net');
define('SIMPLE_DB_NAME', 'mydbname');
define('SIMPLE_DB_USERNAME', 'myusername');
define('SIMPLE_DB_PASSWORD', 'mypassword');

and include them into your MySQL connection class connection.php

include "configuration.php";

class DBConnection 
{
    public function __construct(){
        $this->conn = mysql_connect(SIMPLE_DB_SERVER, SIMPLE_DB_USERNAME, SIMPLE_DB_PASSWORD);
        $this->db = mysql_select_db(SIMPLE_DB_NAME,$this->conn);
    }
}
like image 35
fyousof Avatar answered Sep 29 '22 09:09

fyousof