Is there a difference in using constants or variables in Classes?

3

Is there a difference in using constants or variables in Classes?

    
asked by anonymous 09.06.2016 / 15:23

2 answers

3

Yes, there are differences . Constants can not be changed, regardless of whether they are in classes or not, it is as if they are readonly (read only), in addition they are always static , ie the value is not changed for each object: p>

class Foo {
   const a = 1;
   public $b = 1;

   public function __construct() {
        self::a = 2; //Irá causar erro
   }
}

Another example

class Foo {
   const a = 1;
   public $b = 1;

   public function __construct() {
        $this->b = 2; //Não irá causar erro
   }
}

Constants have these characteristics:

  • Requires PHP 5.3.0
  • They are always public
  • Can not be changed, the value will always be that of the moment it was declared
  • Access is static (since there is no need to change as an object stays)

One tip, you can use the constant function (which in most cases can be somewhat redundant) of either a interface , classe or define :

<?php
define("MAXSIZE", 100);
echo MAXSIZE;
echo constant("MAXSIZE"); // mesma coisa que a linha anterior


interface bar {
    const test = 'foobar!';
}

class foo {
    const test = 'foobar!';
}

$const = 'test';

var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"

Using with spl_autoload (PSR-0 and PSR-4)

There is a small advantage between using const compared to define of PHP, when using installations via composer or any system that is based on PSR-0 or PSR-4 if the class we create uses define and we need only the value of the constant like this:

<?php
namespace Foo;

define('FOO_BAR', 2);

class Baz
{
}

And try to load like that, it will not fire autoload:

<?php
require 'vendor/autoload.php';

var_dump(FOO_BAR);

So even firing autoload, but can not find the class because in PSR we use:

<?php
require 'vendor/autoload.php';

var_dump(Foo::FOO_BAR);

However, if we do this:

<?php
namespace Foo;

class Baz
{
    const BAR = 2;
}

And trying to load like this will work:

<?php
use Foo\Baz;

require 'vendor/autoload.php';

var_dump(Baz::BAR);
    
09.06.2016 / 15:31
3

The name itself says it all.

Constants can not be changed. The variables, as the name says, can be changed.

So briefly, use constants when you need valuable value or important information that is immutable. And the variables you should use in cases where information may vary.

A small fix is that when it comes to classes the correct nomenclature is properties , not variables .

In PHP, when it comes to constants we have some small differences, such as the fact that, for example, a constant can be declared in an interface, different from properties that can not be declared there.

Example:

interface Searchable {
     const FLAG = 1;
}

class Search implements Searchable {}

echo Searchable::FLAG;
echo Search::FLAG;

Recommendations

One of the recommended uses for constants is enumeration simulation in PHP.

For example, suppose my class has a method that accepts the actions "fly", "land" and "hang up". It's not elegant you let the user have to pass the string with these options, so in this case I think the counters have a good utility.

See:

 class Aviao {

      const ACAO_POUSAR = 'pousar';

      const ACAO_VOAR = 'voar';

      const ACAO_DESLIGAR = 'desligar';


       public function acao($acao) {
           if ($acao === self::ACAO_VOAR) {

           } elseif ($acao === self::ACAO_POUSAR) {

           } elseif  ($acao === self::ACAO_DESLIGAR) {

           } else {
              throw new Exception("Ação inválida");
           }
       }

 }




$airbuss = new Aviao();
$airbuss->acao(Aviao::ACAO_VOAR);

Another important way to use constants is when we need to use flags to define some behavior.

Suppose you have a log class, where 1 means "normal" and 2 means "priority". It would be easier to use constants to set these flags

class Log {


       const NORMAL = 1;

       const PRIORIDADE = 2;

       public function write($value, $severity = self::NORMAL) {
            if ($severity == self::NORMAL) {
                 echo $value;
            } elseif ($severity = self::PRIORIDADE) {
                echo "Urgente: $value";
            } else {
               throw Exception("opção inválida");
            }
       }
}

Still using another way to show the importance of constants, see an example of passing default values to a time format. If one day the formatting changed, all you had to do was change the constant, and everything else would change.

Example:

 $time = Time::create(20, 10, 0);

 $time->format(Time::DEFAULT_FORMAT);

NOTE : From PHP 5.6 it is possible to set array to constants.

    
09.06.2016 / 16:18