在php文件中重新定义类,现在生成一个函数

时间:2014-08-24 16:56:15

标签: php

有一个文件myclass.php:

<?php
class Myclass {
    public static function Fun1() {

    }
}

我尝试建立一个自己的框架来使用代码生成:

$class = "MyClass";
$function = "Fun1";
$fname = "myclass.php"
if (class_exists($class) && !method_exists($class, $functionName)) {
    $current = file_get_contents($fname);
    if ($current) {
        $strIndex = strlen($current);
        while ($strIndex-- && $current[$strIndex] != "}");//removing the last '}'
        $current = substr($current, 0, $strIndex);
        $current .= "\tpublic static function $functionName() {\n";//there inserting the new function
        $current .= "\n";
        $current .= "\t}\n";
        $current .= "}\n";
        $current .= "\n";
        file_put_contents($fname, $current);
        require $fname;//I load the file again, but how to redeclare the class?
    }
}

..我收到一条消息:致命错误:无法在第12行的C:\ xampp \ htdocs \ myproj \ index.php中重新声明类MyClass。谢谢。

1 个答案:

答案 0 :(得分:0)

“扩展”Myclass

class MyMyClass extends MyClass
{
    public function SomeNewMethod() {
    }
}

另见Method Overloading