创建一个 PHP 类 -> 在另一个类中创建它的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2303696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:56:52  来源:igfitidea点击:

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

phpclassformsobject

提问by user277813

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:

我创建了一个名为 formChecker.php 的 PHP 类。它验证表单。作为一名 Java 程序员,我想坚持在另一个类中创建此类的实例并从那里运行它的想法。它似乎对我不起作用。以下是演示:

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

GF

回答by Sarfraz

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

只需formChecker在要使用它的类之前包含类文件,例如:

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 :)

谢谢 :)

回答by VolkerK

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

我宁愿将 formChecker 的实例(或实现某个接口的东西)传递给 runFormChecker 的实例。见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);

回答by Ignacio Vazquez-Abrams

Yes, and this is not strange. You would usually create the instance of formCheckerwithin an instance of runFormCheckerthough, and not at the class level.

是的,这并不奇怪。你通常会创建的实例formChecker的实例中runFormChecker的一流水平,虽然,没有。