PHP从另一个类中的一个类创建一个对象


PHP create an object from a class inside another class

我试图为一个类创建一个类对象,但一直遇到一些未知错误。

这是"helper class",它从XML文件中获取内容

<?php
class helperClass {
    private $name;
    private $weight;
    private $category;
    private $location;
    //Creates a new product object with all its attributes
    function __construct(){}
    //List products from thedatabase
    function listProduct(){
        $xmlDoc = new DOMDocument();
        $xmlDoc->load("storage.xml");
        print $xmlDoc->saveXML();
    }
  ?>
}

在这里,我试图从helperClassclass创建一个对象,并从helperClass调用方法listProducts,但如果我尝试实例化helperClass 的对象,代码将不起作用

<?php
//Working code...
 class businessLogic {
    private $helper = null;
    public function __construct() {
    }
    public function printXML() {
        $obj = new helperClass();
        $obj->fetchFromXMLDocument();
        // you probably want to store that new object somewhere, maybe:
        $this->helper = $obj;
    }
}
}
?>

在你们的帮助下,我明白了,这就是我想做的

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        require 'businessLogic.php';
        $obj = new businessLogic();
        $obj->printXML();
        ?>
    </body>
</html>

您的第二个代码片段是错误的。不能在类def内部计算代码。只能在类的方法内部计算。尝试将代码放入构造函数:

class busniessLogic {
  private $helper = null; // defining the property 'helper' with a literal
  // private $helper = new helperClass(); // this would throw an error because
  // it's not allowed in php.
  public function __construct() {
    $obj = new helperClass();
    $obj->listPruduct();
    // you probably want to store that new object somewhere, maybe:
    $this->helper = $obj;
  }
}

这只是在创建对象时如何执行代码的一个示例。

虽然我不会用这种方式。我宁愿把这个物体传进来,或者稍后再设置。

ref依赖项注入

  • http://martinfowler.com/articles/injection.html
  • http://en.wikipedia.org/wiki/Dependency_injection

一旦创建了对象,你就可以对它做任何你想做的事情。例如,对它调用方法(当然,必须定义方法)或将它传递给其他对象。

您的businessLogic类定义不正确。

<?php
include 'helperClass.php';
class busniessLogic {
  function __construct() {
    $obj = new helperClass();
    $obj->listPruduct();
  }
}
$bLogic = new businessLogic();
?>

您试图做的事情是错误的,因为(取自文档)

类成员变量称为"属性"。你也可以看到它们指使用其他术语,如"属性"或"字段",但是出于本参考的目的,我们将使用"属性"。它们是通过使用关键字public、protected或private之一来定义,然后是一个普通变量声明。本声明可包括初始化,但此初始化必须是常量值——也就是说,它必须能够在编译时进行求值,并且必须不依赖于运行时信息才能评估

所以你应该做一些类似的事情

class busniessLogic {
   private $obj;
  function __construct(){
    $this->obj = new helperClass();
    $this->obj->listPruduct();
  }
 }