Asked  7 Months ago    Answers:  5   Viewed   32 times

I want to use a constant in PHP, but I also want to put it inside double quotes like a variable. Is this at all possible?

define("TESTER", "World!");
echo "Hello, TESTER";

obviously outputs "Hello, TESTER", but what I really want is something like:

$tester = "World!";
echo "Hello, $tester";

outputs "Hello, World!".

 Answers

15

Sorry, that's not the way constants in PHP work. You can put variables in double quotes and heredocs but not constants.

Wednesday, March 31, 2021
 
Terry
answered 7 Months ago
60

NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.

You can also serialize your array and then put it into the constant:

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);
Wednesday, March 31, 2021
 
keisar
answered 7 Months ago
27

The print_r() function does not return the string by default. You have to tell it too. When you call it, it automatically writes its output to the output buffer. Since your echo statement is still in the process of being concatenated, it hasn't been echoed yet. So your array gets printed first and then the echo line gets printed after it's finished concatenating.

To make print_r() return its output rather than sending it immediately, specify its second parameter:

echo "Value of FILES['upload'] ".print_r($_FILES['upload'], true)."<br/>";
Wednesday, March 31, 2021
 
Hexaholic
answered 7 Months ago
96

Here's a little function for consideration:

/** Return 22-char compressed version of 32-char hex string (eg from PHP md5). */
function compress_md5($md5_hash_str) {
    // (we start with 32-char $md5_hash_str eg "a7d2cd9e0e09bebb6a520af48205ced1")
    $md5_bin_str = "";
    foreach (str_split($md5_hash_str, 2) as $byte_str) { // ("a7", "d2", ...)
        $md5_bin_str .= chr(hexdec($byte_str));
    }
    // ($md5_bin_str is now a 16-byte string equivalent to $md5_hash_str)
    $md5_b64_str = base64_encode($md5_bin_str);
    // (now it's a 24-char string version of $md5_hash_str eg "VUDNng4JvrtqUgr0QwXOIg==")
    $md5_b64_str = substr($md5_b64_str, 0, 22);
    // (but we know the last two chars will be ==, so drop them eg "VUDNng4JvrtqUgr0QwXOIg")
    $url_safe_str = str_replace(array("+", "/"), array("-", "_"), $md5_b64_str);
    // (Base64 includes two non-URL safe chars, so we replace them with safe ones)
    return $url_safe_str;
}

Basically you have 16-bytes of data in the MD5 hash string. It's 32 chars long because each byte is encoded as 2 hex digits (i.e. 00-FF). So we break them up into bytes and build up a 16-byte string of it. But because this is no longer human-readable or valid ASCII, we base-64 encode it back to readable chars. But since base-64 results in ~4/3 expansion (we only output 6 bits per 8 bits of input, thus requiring 32 bits to encode 24 bits), the 16-bytes becomes 22 bytes. But because base-64 encoding typically pads to lengths multiples of 4, we can take only the first 22 chars of the 24 character output (the last 2 of which are padding). Then we replace non-URL-safe characters used by base-64 encoding with URL-safe equivalents.

This is fully reversible, but that is left as an exercise to the reader.

I think this is the best you can do, unless you don't care about human-readable/ASCII, in which case you can just use $md5_bin_str directly.

And also you can use a prefix or other subset of the result from this function if you don't need to preserve all the bits. Throwing out data is obviously the simplest way to shorten things! (But then it's not reversible)

P.S. for your input of "a7d2cd9e0e09bebb6a520af48205ced1" (32 chars), this function will return "VUDNng4JvrtqUgr0QwXO0Q" (22 chars).

Wednesday, March 31, 2021
 
samrap
answered 7 Months ago
86

Clearify the question: What is the advantage of a configuration container over globally define()ed configuration contstants?

The advantages are all the advantages that OOP offers: Data Abstraction and Encapsulation, Inheritance, Polymorphism and better design pattern integration.

The readers of this thread seem a little confused and focus on your class rather than the main question. To also clearify this, let me give you an example:

class Configuration
{
    protected $someValue;
}

class ConfigurationDev extends Configuration
{
    protected $baseUrl = 'http://devel.yoursite.com/';
}

class ConfigurationLive extends Configuration
{
    protected $baseUrl = 'http://www.yoursite.com/';
}

index.php:

<?php
$config   = new ConfigurationDev;
$tracking = new Tracking($config);
...

class Tracking:

class Tracking
{
    public function __construct(Configuration $config) {
        if ($config instanceof ConfigurationLive) {
            // We are in live environment, do track
        } else {
            // Debug Notice: We are NOT in live environment, do NOT track
        }
    }
}

Explanation of the scenario:

Imagine you want to track users, but only on the live system, not on your development system. The Tracking class expects a live configuration but aborts (without impact) if its not the live config.

Your class with const is not the best, because const implies you do not want to change the variables. Do not use the variable for values that may change. You shouldn't use static stuff either because it mostly conflicts with dependency injection. Pass real objects!

Your function public static function getValueDependingOnURL() should be placed in a Helper class, not in a Constant/Configuration container either.

class Helper
{
    protected $config;

    public function __construct(Configuration $config) {
        $this->config = $config;
        return $this;
    }

    public function getValueByUrl($url) {
        if ($url == 'something') {
            return $config->getMinValue();
        } else {
            return $config->getMaxValue();
        }
    }
}

Now you can have different sets of configuration which the helper class relies on:

$config = new ConfigurationLive;
$helper = new Helper($config);
$value  = $helper->getValueByUrl($_SERVER['REQUEST_URI']);

There is a lot of best practice design pattern stuff, code style and OOP in my examples, learn about those and you will gain a much higher level of software engineering than the readers of your question. Good luck!

Saturday, May 29, 2021
 
macha
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :