7

I have created a PHP class called formChecker.php. It validates a form. As a Java programmer, I would like to stick with the idea of creating an instance of this class in another class and run it from there. It doesn't seem to be working for me.The following is a demonstration:

class formChecker{

  ..... validation functions go here

}

class runFormChecker{

....  create instance of formchecker here and use it's methods etc.

}

Can this be done? What I'm thinking of is developing a number of classes that can be run seperately.

GF

VolkerK
  • 95,432
  • 20
  • 163
  • 226
user277813
  • 159
  • 1
  • 2
  • 12

3 Answers3

8

Just include the formChecker class file just before the class you want to use it in eg:

include "formChecker.php"

class runFormChecker{

     function __construct() {
      $obj = new formChecker;  // create instance
      // more processing............
     }  
}

If however, you have both classes in one file (which is bad), then no need to include the file, you can create the instance of that straight away eg:

class formChecker{
  // ............
}

class runFormChecker{

     function __construct() {
      $obj = new formChecker;  // create instance
      // more processing............
     }  
}

More information here.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Isn't it bad to "include" the file also? Isn't this the same thing as having both classes in one file? – user277813 Feb 21 '10 at 22:22
  • 1
    @grungefreak1:how is this bad? if you put classes in its own files and include them in one other file, they will be one again but in running script only but outside the app, they remain in their own files which makes easier to maintain them. – Sarfraz Feb 22 '10 at 01:13
  • Point taken. However, I will go with the process of passing one object into another's constructor as it is more in line with my OOP ideas.GF – user277813 Feb 22 '10 at 22:15
8

I'd rather pass the instance of formChecker (or something that implements a certain interface) to the instance of runFormChecker. see http://en.wikipedia.org/wiki/Dependency_injection

Could be as simple as

interface FormChecker {
  public function foo($x);
}

class MyFormChecker implements FormChecker
  public function foo($x) {
    return true;
  }
}

class RunFormChecker {
  protected $formChecker=null;
  public function __construct(FormChecker $fc) {
    $this->formChecker = $fc;
  }

  // ....
}

$rfc = new RunFormChecker(new MyFormChecker);
VolkerK
  • 95,432
  • 20
  • 163
  • 226
0

Yes, and this is not strange. You would usually create the instance of formChecker within an instance of runFormChecker though, and not at the class level.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358