I’ve been writing a lot of php lately, and mostly I’ve been struck by how much it looks like Perl, despite the average php-fan’s assertions to the contrary. Granted, this likely has a lot to do with who’s writing it, rather than being intrinsic to the language itself, but, still, it looks and feels an awful lot like Perl.
Which makes it all the more irritating when I try to do something that I figure it ought to be able to do, and it flatly refuses to do it.
Today, for example, I tried to persuade it to auto-generate some code for me, so that I wouldn’t have to.
The scenario is that I have N database tables, each with MN fields. I’m writing a class to encapsulate each of the N tables, and, for each of those, I’d then have to write the MN accessor methods. That’s clearly unacceptable, so after the first two or three, I attempted to automate the process. What I came up with was something like the following. In the table class, I might have:
foreach ($fields as $field) { gen_function($class, $field); }
Then, gen_function
will be in some parent class, and will look something like:
function gen_function($class,$field) { eval(" function $class::$field() { $args = func_get_args(); return getset($this, '$field', $args); } "); }
Now, that doesn’t work, so don’t expect it to. But there’s got to be a way to do that, right? Oh, and function getset
exists and works, so just pretend it does what you expect it to. That’s neither here nor there for the purpose of this conversation.
I asked on #php how (or if) one might go about creating a function in someone else’s namespace, and was met by a collective blank stare, so either I’m not asking the right question, or I’m using Perl-specific terms in my question.
I know that some of my readers are php wizards, so perhaps one or more of you can shed some light on the right way to do what I’m trying to do. Or perhaps tell me that PHP simple forbids this kind of monkeying around with namespaces. Or perhaps … dunno. Is there another way to get around this? The purpose of computers is to do things for me so that I don’t have to. Writing the same 4 lines of code repeatedly is a *bad* thing.