Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a PHP Class -> Create an object of it in another class

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

like image 536
user277813 Avatar asked Feb 20 '10 20:02

user277813


2 Answers

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);
like image 191
VolkerK Avatar answered Oct 29 '22 10:10

VolkerK


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....

Thanks :)

like image 21
Sarfraz Avatar answered Oct 29 '22 11:10

Sarfraz