Should I store variables used in only one class method, or declare them as class properties?

I was wondering if a class property is created and used in only one class method, if it is a class property at all, or should there be only a local variable accessible only for this class?

For example, whether to save a variable used in only one method as a local variable, such as:

class myClass { public function myMethod() { $_myVariableUsedOnlyOnce = "Hello World"; echo $_myVariableUsedOnlyOnce; } } 

Or should I make the variable a private property of the class as follows:

 class myClass { private $_myVariableUsedOnlyOnce; public function myMethod() { $this->_myVariableUsedOnlyOnce = "Hello World"; echo $this->_myVariableUsedOnlyOnce; } } 

Which approach "smells"? What are the benefits of creating all the properties of a class of method variables other than when I need to print_r () the whole object for debugging purposes?

thanks

+6
source share
5 answers

If you need to keep it in all function calls, the class property would be better to move as the object does. You can also use it for other reasons in the future in other functions. However, it adds overhead.

As a rule, the class should have some real analogue, therefore, if your variable corresponds to something that makes sense, for example. a person’s class has a height of $, then he belongs as a property of the class. Otherwise, if this is just part of the method’s internal calculations, then it really does not belong to the class, for example. the person does not have $ shoelaceIterator or anything else.

I would say that the intricate design of the object would be a smell rather than a potentially small amount of memory (although this depends on how large the variable is).

+4
source

These local variables are not properties of your object.

They do not define your object, then they should not be declared a private member.

+1
source

First, I would ask if you really need a variable / property if you use it only once. As for what “smells,” the property is stored in memory for the entire life of the object, while the variable is only in memory until the method completes execution.

0
source

If you do not need a variable outside the method, this should not be any property of the class. Moreover, access to local variables is faster.

0
source

In a simple design, I suggest you make your choice according to what the attribute / property should be.

In pure performance conditions, one static attribute is better, because memory space will not be allocated with every instance of the class.

0
source

Source: https://habr.com/ru/post/910921/


All Articles