【问题标题】:Redeclaring class in php file where now generated a function在现在生成函数的 php 文件中重新声明类
【发布时间】:2014-10-17 21:43:05
【问题描述】:

有一个文件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。谢谢。

【问题讨论】:

  • 在同一个命名空间中不能有两个同名的类声明。引擎如何知道您在使用它时打算使用 2 个中的哪一个?
  • 您正在尝试向现有类添加方法?这非常不像 PHP(更像 Ruby 或 JavaScript)。 Runkit 允许:pt2.php.net/manual/en/function.runkit-method-add.php
  • @MichaelBerkowski 这不像 PHP,这是非常糟糕的 OO。子类化Myclass 在设计上会好很多,不是吗?
  • @wumm 确实糟糕的 OO,这就是为什么在链接问题中建议使用装饰器的原因。

标签: php


【解决方案1】:

“扩展”我的班级

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

另见Method Overloading

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 2016-08-11
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多