Share variables between classes in PHP

2

I have several classes as in the example.

class clase1 extends padreclase1 {
 var $variable1 = 'valor1';
  var $variable2    = 'valor2';
}

class clase2 extends padreclase2 {
var $variable1  = 'valor1';
var $variable2  = 'valor2';
}

The value of the variables will be the same in all cases, but I would not like to have to repeat their writing in all classes.

How can I do to put those variables in a file or similar and then be inserted at the beginning of each class? Since they must be attributes of each class.

    
asked by Webemus GroupJoom 19.09.2018 в 08:39
source

1 answer

2

For this case, if you have different classes in origin and all yours have to:

1.- inherit from some defined classes of your framework, different from each other.

2.- contain attributes in each of them, equal

The solution is to use traits: link

For example, in your case, you could do:

trait VariablesGeneralesTrait {
    var $variable1 = 'valor1';
    var $variable2 = 'valor2';
}


use VariablesGeralesTrait;
class clase1 extends padreclase1 {
 trait VariablesGenerales;
}


use VariablesGeneralesTrait;
class clase2 extends padreclase2 {
 trait VariablesGenerales;
}

With this, a "lateral inheritance" occurs, so that all the classes that "use" the trait, have the same attributes (and even methods).

    
answered by 19.09.2018 / 09:19
source