Create a PHP class & # 8594; Create its object in another class

I created a PHP class called formChecker.php. He checks the form. As a Java programmer, I would like to stick to the idea of ​​instantiating this class in another class and running it from there. This does not seem to work for me. Below is a demo:

class formChecker{ ..... validation functions go here } class runFormChecker{ .... create instance of formchecker here and use it methods etc. } 

Can this be done? I am thinking of developing a number of classes that can be executed separately.

Gf

+7
object php class forms
source share
3 answers

I would rather pass an instance of formChecker (or something that implements a specific interface) to the runFormChecker instance. 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); 
+8
source share

Just include the formChecker class formChecker immediately before the class you want to use, for example:

 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 there is no need to include the file, you can instantiate this example, for example:

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

More info here ....

Thanks:)

+8
source share

Yes, and this is not strange. Usually you create an instance of formChecker in an instance of runFormChecker , but not at the class level.

0
source share

All Articles