constant php code example

Example 1: php const

<?php
    define('CONSTANT', 'Hello world !');
    const CONSTANT = 'Hello world !';
    const NEW_CONSTANT = CONSTANT.' And beyond...';
    const ANIMALS = array('dog', 'cat', 'ant');
    define('ANIMALS', array('dog', 'cat', 'ant'));
?>

Example 2: how to store connection object in the constant in php

<?php

include_once('IConnectInfo.php');

class Database implements IConnectInfo
{

    private static $instance = null;
    private $conn;

    private $server = IConnectInfo::HOST;
    private $currentDB = IConnectInfo::DBNAME;
    private $user = IConnectInfo::UNAME;
    private $pass = IConnectInfo::PW;

    private function __construct()
    {
        try {
            $this->conn = new PDO("mysql:host=$this->server;dbname=$this->currentDB", $this->user, $this->pass
            );
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->conn->exec('set names utf8');
            echo $this->server . " connected successfully" . PHP_EOL;
        } catch (PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
            die;
        }
    }

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new Database();
        }

        return self::$instance;
    }

    public function getConnection()
    {
        return $this->conn;
    }


    public function getSelectQueryResult($query = '')
    {
        try {
            $query = $this->conn->prepare($query);
            $query->execute();
            return $query->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            echo $query . "<br>" . $e->getMessage();
        }
    }
}

Tags:

Php Example