Store PHP class settings in variables or return them from methods

I see two different implementations when people process classes that extend other classes and provide functionality based on specific settings within the class.

  • Variables are used to store settings.
  • Methods are used to return settings.

Using variables:

class Model { var $fields = array(); function getFields() { return array_keys($this->fields); } function getRules() { return $this->fields; } } class Person extends Model { var $fields = array( 'name' => array('maxLength'=>10), 'email' => array('maxLength'=>50, 'validEmail'=>true), ); } 

Using Methods:

  class Model { function getFields() {} } class Person extends Model { function getFields() { return array('name','email'); } function getRules() { return array( 'name' => array('maxLength'=>10), 'email' => array('maxLength'=>50, 'validEmail'=>true), ); } } 

Both examples achieve the same results, I can do things like $person->getFields() and $person->getRules() , but in the example method I don’t like the duplicate field list, because the fields are actually defined as in $person->getFields() and $person->getRules() , and it must compute the array every time it is requested using the method. On the other hand, I do not like that each object saves all the settings in a variable. It is like a waste of resources. So I'm just wondering which is better.

My main questions are:

  • Is there a performance reason to choose one path after another? 2)
  • Is there OOP logic / ease of programming / another reason to choose one path through another?
+4
source share
2 answers

Of the few benchmarks - times are very similar - an exception, although

 return array('name','email'); 

much faster than

 return array_keys($this->fields); 

Running 10,000 operations for each method gave these averages:

 Variable: getFields 0.06s getRules 0.05s Method: getFields 0.04s getRules 0.05s 

To answer the second question - it depends on your use case - if the data stored in these objects is static or if they will be obtained from another data source / configuration file.

The next question, why not use the properties of the object?

 class Person extends Model { protected $name protected $email public function getName() { return $this->name; } public function getEmail() { return $this->email; } } 
+1
source

My opinion is to choose what you are comfortable with, there is no loss in performance or productivity from use. You better save the cost of data processing.

For me, I use the properties of an object, it looks clear when you look at a class to store such properties by default, and if you want to override them, use this beautiful syntax:

 array()+array() 
+1
source

All Articles