简体   繁体   English

在另一个类的构造函数中实例化一个类

[英]Instantiate a class in another class's constructor

I'd like to instantiate a class once, within another class' constructor, and then have access to it from all the functions of the class. 我想一次在另一个类的构造函数中实例化一个类,然后从该类的所有功能对其进行访问。

If you look at the following class, you can see that in function foo, I instantiate CLibrary and then call a function (callFn). 如果查看下面的类,则可以看到在foo函数中,我实例化了CLibrary,然后调用了一个函数(callFn)。 This works fine. 这很好。

What I would like to do is to instantiate CLibrary in the constructor (see comment) and then be able to use that variable ($library) in foo to access callFn (see the comments). 我想做的是在构造函数中实例化CLibrary(请参见注释),然后能够在foo中使用该变量($ library)来访问callFn(请参见注释)。

But this does not seem to work. 但这似乎不起作用。

Can anybody help? 有人可以帮忙吗?

class CTweeting {
  private $library;
  private $ROOT;
  private $PHP_CLASSES;

  function __construct) {
        $this->ROOT        = $_SERVER['DOCUMENT_ROOT'];
    $this->PHP_CLASSES = $this->ROOT . "/php/classes/";
    require_once($this->PHP_CLASSES . 'CLibrary.php'); 
    //$library = new CLibrary(); // ** I would like to uncomment this line **



  public function foo() {
    $library = new CLibrary(); // …. delete this line
        $library->callFn();  // … and change this line to ‘$this->library->callFn();’
  }
}  

The $library variable can be used in your class constructor by doing $this->library 通过执行$this->library可以在类构造函数中使用$ library变量

So the code should look like this: 因此,代码应如下所示:

class CTweeting { private $library; CTweeting类{私有$库; private $ROOT; 私人$ ROOT; private $PHP_CLASSES; 私人$ PHP_CLASSES;

     function __construct) {
            $this->ROOT        = $_SERVER['DOCUMENT_ROOT'];
        $this->PHP_CLASSES = $this->ROOT . "/php/classes/";
        require_once($this->PHP_CLASSES . 'CLibrary.php'); 
        $this->library = new CLibrary(); 

........
.......
........

Here is a cleaned up version, using $this->library in the constructor and the foo() method 这是一个清理后的版本,在构造$this->library中使用$this->libraryfoo() method

class CTweeting {
  private $library;
  private $ROOT;
  private $PHP_CLASSES;

  function __construct() {
     $this->ROOT        = $_SERVER['DOCUMENT_ROOT'];
     $this->PHP_CLASSES = $this->ROOT . "/php/classes/";
     require_once($this->PHP_CLASSES . 'CLibrary.php'); 
     $this->library = new CLibrary();
  }

  public function foo() {
     $this->library->callFn();
  }
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM