关于使用 php 中另一个 class 中存储的 class 的方法的说明

Explanation about using a method of a stored class from another class in php

所以我正在审查来自 PHPWord 的源代码,我已经查看了所有内容,但无法弄清楚这段代码是如何工作的。

class PHPWord_Shared_XMLWriter {

/**
 * Internal XMLWriter
 *
 * @var XMLWriter
 */
private $_xmlWriter;

public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTemporaryStorageFolder = './') {
    // Create internal XMLWriter
    $this->_xmlWriter = new XMLWriter();
    ...
}
}

所以根据我对 php 的理解,访问 $this->_xmlWriter 方法的唯一方法是这样调用它:

$testClass= new PHPWord_Shared_XMLWriter();
$testClass->_xmlWriter->startDocument();

然而,在这段代码中theDocProps.php这行代码是实现的:

$objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY);
$objWriter->startDocument('1.0','UTF-8','yes');

这是如何运作的?我无法复制它,但是当我在文件中使用它时它会起作用。需要明确的是,PHPWord_Shared_XMLWriter 没有定义名为 startDocument() 的方法。我觉得我错过了一些非常简单的东西,但我什至无法正确搜索它。

谢谢!

您需要查看 the entire definition of the class PHPWord_Shared_XMLWriter (source here). It uses the __call magic method 以将方法调用传递给 _xmlWriter:

 /**
  * Catch function calls (and pass them to internal XMLWriter)
  *
  * @param unknown_type $function
  * @param unknown_type $args
  */
 public function __call($function, $args)
 {
     try {
         @call_user_func_array(array($this->_xmlWriter, $function), $args);
     } catch (Exception $ex) {
         // Do nothing!
     }
 }

通过在 $this->_xmlWriter 上使用 call_user_func_array,它会导致所有无法访问或未定义的方法传递给 _xmlWriter 属性。

来自文档:

__call( unknown_type $function, unknown_type $args )
    Catch function calls (and pass them to internal XMLWriter)
    Parameters
        $function
            unknown_type
            $function
        $args
            unknown_type
            $args