将类中的内容作为字符串返回

时间:2014-07-31 08:14:06

标签: php regex tokenize

如何将类的全部内容作为字符串获取?

您好,

在我目前的项目中,我有n个模块,每个模块有3个文件。每个文件都包含一些功能:

第一单元 - FileOne.php:

<?php 
    function method_one() {
        return;
    }

    function method_two() {
        return;
    }
?>

第一单元 - FileTwo.php:

<?php 
    function method_one() {
        return;
    }
?>

第一单元 - FileThree.php:

<?php 
    function method_one() {
        return;
    }
?>

在项目环境中,每个模块将根据文件解析为缓冲区。 此缓冲区稍后将写入临时php文件。最后,我们有3个临时文件,包含所有模块的所有内容。

示例:

tmp.FileOne.php contains all functions of each FileOne.php file for each module
tmp.FileTwo.php contains all functions of each FileTwo.php file for each module
tmp.FileThree.php contains all functions of each FileThree.php file for each module

我想将它们合并到一个文件中,而不是为一个模块管理三个独立的文件。我虽然为每个文件使用类调用。但是我找不到一个很好的解决方案,可以将所有方法作为字符串从一个文件中的给定类中获取。

示例: ModuleOne.php

<?php

class FileOne {

    function method_one() {
        return;
    }

    function method_two() {
        return;
    }
}

class FileTwo {

    function method_one() {
        return;
    }
}

class FileThree {

    function method_one() {
        return;
    }
}
?>

我曾尝试使用PHP Tokenizer,但找不到可行的解决方案,只能找到XYZ类的内容。

这样的事情会很完美:

echo GetClassContentAsString( 'FileOne' );

输出:

"function method_one() { return; } function method_two() { return; }"

1 个答案:

答案 0 :(得分:1)

确定。正如我所见,你无法将类作为字符串。但是你可以使用reflection来获取定义类的行。

class asdf
    {

    }

$reflection_class = new ReflectionClass('asdf');

$result = implode(
    ''
    , array_slice(
        file($reflection_class->getFileName())
        , $reflection_class->getStartLine() - 1
        , $reflection_class->getEndLine() - $reflection_class->getStartLine() + 1));

echo $result;

// class asdf
//     {
// 
//     }

但是您可以使用类定义检索额外的符号。

1;class asdf
    {

    }1;