0

There is a file myclass.php:

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

    }
}

and i try to make an own framework where to use a code generation:

$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?
    }
}

.. and i get a message: Fatal error: Cannot redeclare class MyClass in C:\xampp\htdocs\myproj\index.php on line 12. Thank you.

user2301515
  • 4,903
  • 6
  • 30
  • 46
  • 1
    You can't have 2 declarations of the class with the same name in the same namespace. How would the engine know which one of the 2 you intended when using it? – Wrikken Aug 24 '14 at 16:57
  • You are trying to add a method to an existing class? That's very un-PHP-like (more like Ruby or JavaScript). Runkit allows it: http://pt2.php.net/manual/en/function.runkit-method-add.php – Michael Berkowski Aug 24 '14 at 16:59
  • See also: [How to add a method to an existing class](http://stackoverflow.com/questions/3011910/how-to-add-a-method-to-an-existing-class-in-php) – Michael Berkowski Aug 24 '14 at 17:00
  • 1
    @MichaelBerkowski That's not un-PHP-like, that's very bad OO. Subclassing `Myclass` would be much better in design, wouldn't it? – idmean Aug 24 '14 at 17:23
  • @wumm Indeed bad OO, and that's why the Decorator is suggested in the linked question. – Michael Berkowski Aug 24 '14 at 18:15

1 Answers1

0

"Extend" Myclass

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

see also Method Overloading:

Brad Kent
  • 4,982
  • 3
  • 22
  • 26