PHP: OOP and Methods

I was wondering how to implement methods in a class. Can someone explain to me what it means if you are doing OOP in a procedural style?

Here's an example:

class Fld extends Model {

  private $file;
  private $properties = array();

  public function init($file) { 
    $this->file = $file;
    $this->parseFile();
  }

  private function parseFile() {
  // parses the file
    foreach($this->file as $line) {
      //..................
    }
    $this->properties = $result;
  }

}

      

I mean, is it good to have methods like this that do operations on such properties of a class. Or should I pass a property of the class as a parameter of the method ... I mean it will throw an error if the property of the file is not declared.

+2


a source to share


2 answers


If a file is required for an object, it must be a parameter in your constructor.

class Fld extends Model {

    private $file;
    private $properties = array();

    function __construct($file) {
        $this->file = $file;
    }

    public function parse() {
        foreach($this->file as $line) {
            /* ... */
            $this->properties = $result;
        }
    }
}

      



When you have a method in your class that does not use any of the class properties, you should consider making that method static, or even creating a separate class for that method.

+3


a source


I think people describe code as "procedural OOP" where methods within a class tend to be very long and complex.

Martin Fowler's book "Refactoring" describes the long method as a "code smell" which hints that parts of its code can be broken down into smaller methods or separated into other classes.

see: http://books.google.co.uk/books?id=1MsETFPD3I0C&lpg=PP1&dq=refactoring&pg=PA76#v=onepage&q&f=false



I think your code is fine. Just remember as disposable class objects. Typically, such a "syntax service" must be created, used, and discarded. Then you don't have to worry about old properties causing confusion if they are reused.

As eteubert suggests, passing instrumentation in a constructor helps clients understand that an object is being created for a specific purpose.

+1


a source







All Articles