Practical use of Constant scalar expressions in PHP and other languages

6

In PHP 5.6 we will have a feature named Constant scalar expressions . The manual provides some examples, but the main focus would be:

  • How to correctly use the feature without undoing an anti-pattern ?
  • Do other languages implement this kind of feature? How does it work and is it used in them?
  • What% of Bootstrap% would be an example of this concept?
asked by anonymous 16.07.2014 / 23:06

3 answers

3

This functionality is not widespread among other languages and there is also no good practice found by common sense, so my opinion is that this new functionality will be very well used by some and others will be used as a new form of "gambiarra" .

Personal opinion:

Good use :

  • Calculate default values for method arguments;

In this example, if you want to change the default limit from 5 to 10, it will change in one place:

<?php
class Foo {
    const DEFAULT_LIMIT = 5;

    public function bar($limit = self::DEFAULT_LIMIT) {
        //code
    }

    public function wonka($limit = self::DEFAULT_LIMIT) {
        //code
    }
}

Misuse :

  • Calculation of urls and paths in constants, since this can be used as it always has been, using define() or even creating specialized objects and methods to deliver Path information for example.
22.07.2014 / 20:05
2

An interesting example is configuration variables.

For example: suppose a scenario where services are consumed, or an approval base, or production. These services come from a URL, which varies, depending on the database in question.

Thus, the URLs for these services can be determined by a flag that determines whether the application is in production mode or homologation. See the following example:

// variavel que define ambiente - homogação ou produção
$isHomolog = true;

// constantes para ambiente de homologação
const URL_SERVICO_1_HOMOLOG = "http://homolog1.com";
const URL_SERVICO_2_HOMOLOG = "http://homolog2.com";

// constantes para ambiente de produção
const URL_SERVICO_1_PRODUCTION = "http://production1.com";
const URL_SERVICO_2_PRODUCTION = "http://production2.com";

// constantes utilizadas para os serviços
const URL_SERVICO_1 = $isHomolog ? URL_SERVICO_1_HOMOLOG : URL_SERVICO_1_PRODUCTION;
const URL_SERVICO_2 = $isHomolog ? URL_SERVICO_2_HOMOLOG : URL_SERVICO_2_PRODUCTION;

In this example constants are defined for the approval and production environment. In addition, the variable $isHomolog identifies whether the environment is type-approved (value true ) or production (value false ). Therefore, the service variables used by the system URL_SERVICO_1 and URL_SERVICO_2 have their value conditioned to the environment variable $isHomolog .

The advantage of this mechanism is that there is no need to exchange multiple URLs in the system, depending on your environment: approval or production.

Note that the same behavior can be obtained with variables that are not constants, but the creation of constants guarantees that they will not be modified by the application. Note that this possibility of condition in its creation is not allowed after the constants are defined, which guarantees its correct use to the system.

Another interesting case is the concatenation of Strings to create a constants. in earlier versions of PHP, when trying to create String constants based on parts of other Strings, the following message is displayed: "PHP Parse error". Now this is allowed. This is exemplified in the link shown in the question itself. Here's an example:

// Constant declarations
const PHP = "PHP";
const LOBBY = "Lobby";
const PHPLOBBY = PHP . " " . LOBBY;
echo PHPLOBBY . "\n";
echo "\n=====================\n\n";

Notice that the PHPLOBBY constant is defined by a concatenation of Strings. This is useful when constants are used in the system, but concatenation is also used. In order to make the code cleaner, a constant being the result of several concatenation is often very useful. This kind of assignment to constants is already possible, in both Java and C # .NET.

    
21.07.2014 / 13:36
0

Dude, I'll try to explain a good use with an example.

In the PHP code below you can see all variants of scalar expression for PHP coding, but let's talk about them. We have the flexibility to use this feature in "Constant Declarations", "Class Constant Declarations", "Class Property Declarations", "Argument Declarations", "Static Variable Declarations". As you can see the "PHPLOBBY" constant in the PHP code below, it is a result of the concatenation of "PHP" and "lobby" with constant empty space between them.

If you try the same approach in earlier versions of PHP it will give "Parse Exception". The most important thing for me is the flexibility in the argument statements. We added example of method in our class "PhpLobby" called "is_true". Basically what it does is if it does not pass argument that executes the "Constant Scalar Expressions" ("$ c = self :: NUMBER == 9?" True ":" False ".) We check if the constant" Number "is equal to 9 and then assign a value to variable $ c that we have the flexibility to do this only in PHP 5.6 and not in the previous PHP version.

    <?php
echo "\n===PHPLobby Constant Scalar Expressions ===\n";

// Constant declarations
const PHP = "PHP";
const LOBBY = "Lobby";
const PHPLOBBY = PHP . " " . LOBBY;
echo PHPLOBBY . "\n";
echo "\n=====================\n\n";

// Class Constant Declarations
class PhpLobby {
    const PHP = PHP . " ";
    const LOBBY = self::PHP . LOBBY . "\n";
    const NUMBER = 5 + 4 . "\n";

    // static variable declarations
    static $math = 5 + 4 . "\n";
    static $math2 = 9 - 5 . "\n";
    static $math3 = self::NUMBER - 4 . "\n";

    // class property declarations
    public $php = "PHP " . "Lobby\n";
    public $number = 5 + 4 . "\n";

    // argument declarations
    function is_true($c = self::NUMBER == 9 ? "True" : "Wrong") {
        return $c . "\n";
    }
}
echo PhpLobby::LOBBY;
echo PhpLobby::NUMBER;
echo "\n=====================\n\n";

// Class Property Declarations
$phpLobby = new PhpLobby();
echo $phpLobby->php;
echo $phpLobby->number;
echo "\n=====================\n\n";

// Argument Declarations
echo $phpLobby->is_true(); // weeeeee magic!
echo $phpLobby->is_true(10); // result will be 10 as expected
echo "\n=====================\n\n";

// Static Variable Declarations
echo PhpLobby::$math;
echo PhpLobby::$math2;
echo PhpLobby::$math3;

echo "\n===========================================\n";
?>

In addition, here is the list of what can be used with it:

Supported operation:

    • - Addition
    • - Subtraction
    • - Multiplication
  • / - Division
  • % - Modulus
  • ! - Boolean Negation
  • ~ - Bitwise Negation
  • | - Bitwise OR
  • & - Bitwise AND
  • ^ - Bitwise XOR
  • < < - Bitwise Shift Left
  • > > - Bitwise Shift Right
  • . - Concatenation
  • ? - Ternary Operator
  • 21.07.2014 / 19:23