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

时间:2014-01-01 13:14:40

标签: php

我想在另一个类的构造函数中实例化一次类,然后从该类的所有函数中访问它。

如果查看下面的类,可以看到在函数foo中,我实例化了CLibrary,然后调用了一个函数(callFn)。这很好。

我想要做的是在构造函数中实例化CLibrary(请参阅注释),然后能够在foo中使用该变量($ library)来访问callFn(参见注释)。

但这似乎不起作用。

有人可以帮忙吗?

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();’
  }
}  

2 个答案:

答案 0 :(得分:0)

通过执行$this->library

,可以在类构造函数中使用$ library变量

所以代码应如下所示:

类CTweeting {   私人$ library;   私人$ 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(); 

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

答案 1 :(得分:0)

这是一个已清理的版本,在构造函数中使用$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();
  }
}