Php Code-Generator

So what I’m trying to do is “modifying php code programmatically”.

I thought that there should be already some library that could help me out, XPath, HTML DOM Parser this is what I’m looking for but for PHP.

How I’d like it to work is, you create a object, pass to the constructor a file location (/var/www/test/TestClass.php), and then you will be to:

  • extend this class

  • add some parameters to the file

$obj->addParam(‘name’);

  • add/update methods;

It’s like “reflection” but here you’d be able to add code, and not just get some info about the class.

I don’t really know where to start, any idea on how to build this is highly appreciated

Even though you could build workarounds (e.g. use PHP’s magic methods) PHP clearly was not designed for this. Not sure, what you try to achieve, but if it’s crucial for your project maybe try another language? In Smalltalk for example you can do this kind of thing, as everything there is an object, even classes themself.

I don’t need this for a project, it’s a hobby, or more like a dream :)

I’d like to get to the point where it would be possible to write code only using your mouse,

I see. But why on earth did you pick PHP then? :) Have a look at Lisp (e.g. Clojure). It’s much better suited to build something like self-modifying code.

You need to stop helping wadim, Mike. This is the first step towards machine sentience and the inevitable robot uprising…

BTW this topic should be moved to the miscellaneous section.

I’ve just finished a project and now i have a little bit more free time.

Now here’s the problem:




private function getFunctionCode($functionName) {


            $source = explode("\n", $this->_code);


            $class = new ReflectionClass(str_replace('.php', '', $this->_filename));

            $func = $class->getMethod($functionName);


            $startLine = $func->getStartLine() - 1;

            $endLine = $func->getEndLine();

            $length = $endLine - $startLine;


            return array_slice($source, $startLine, $length);

        }



I’m using reflection to find out where the function begins and ends. The problem is that I don’t know if it’s safe to use.




new ReflectionClass(str_replace('.php', '', $this->_filename));

str_replace('.php', '', $this->_filename) // this here get's converted to a string something like 'User'



And now the question is - Is this thing safe to use ? Lets say that I have a model ‘User.php’ in my protecte.models and a User.php in protected.modules.modulename.models how will this work out ?

And if I can’t use reflection here maybe you could point me out to something else.