A
A
Andy912017-02-23 01:25:23
OOP
Andy91, 2017-02-23 01:25:23

OOP. whether to store data in an object?

I'm sorry for the probably stupid question, but it's hard to formulate it, so I don't even know how to google this topic. Prompt to the beginner as more correctly concerning OOP to store the data. It's hard to explain so far, so here are two examples:

class Class{
  function FUNC(){
    // код для получения DATA
    return Data;
  }
}

obj = new Class();
d = obj->FUNC();

or so
class Class{
  private DATA

  function FUNC(){
    if( this->DATA ){
      return this->DATA;
    } else {
      // код для получения DATA;
      this->DATA = DATA;
      return DATA;
    }
  }
}

obj = new Class();
d = obj->FUNC();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xfg, 2017-02-23
@xfg

Not both.

class Class {
  private $data;

  public function __construct($data) {
    $this->data = $data;
  }
  public function data() {
    return $this->data;
  }
}

The code for getting data lives outside the class. To understand why this is so, rename Class to Auto, for example, and data to color, for example. In general, the point is that an object must have a state (object properties) and may have behavior (object methods) that change this state. It should be obvious. Sometimes there are exceptions. Rarely. Almost always, you can make true OOP.
Now you, unfortunately, have procedural code wrapped in OOP nomenclature :(

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question