KBD

Keith Devens .com

Friday, December 5, 2008 Flag waving
The three chief virtues of a programmer are: Laziness, Impatience and Hubris. – Larry Wall (Programming Perl)
← CMS-driven site, here we go?Firefly gag reel →

Daily link icon Sunday, March 9, 2003

Is it possible to load classes dynamically in PHP?

The subject says it all. Is it possible to load classes dynamically in PHP? In other words, can I say new $foo, where $foo is a string containing the name of a class? Hmm...

Ok, that answers that... it turns out it's possible to say "new $foo", but not "new "Foo"".

The following works and prints the constructor's message:

<?php
class Foo{
    function 
Foo(){
        echo 
"Foo constructor called!<br>";
    }
}

$foo "Foo";
$f = new $foo;
?>

But if the last line is $f = new "Foo", it doesn't.

Anyway, this is good enough for my purposes. I wanted to be able to load classes dynamically in my CMS, based on information in a configuration file. If I couldn't do this, I would have gotten around it by dynamically calling a function, which I was sure PHP could do.

Hey, and it's not even case sensitive Smiley I can say $f = new $foo; where $foo is "foo".

← CMS-driven site, here we go?Firefly gag reel →

Comments XML gif


Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

December 2008
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
28293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 4 posts

Recent comments XML

Girls, please don't get breast implants

I have 34 A breast but at 22 years​old they seem to be growing again​which ...

76.64.120.153: Dec 3, 10:00am

Perl 6 1.0 in March?

Doh, my mistake. I'm aware of the​relation between Parrot and Rakudo​but I'...

Keith: Dec 2, 1:03am

Free image hosting sites

Well, TinyPic has this in its​FAQ:

> Images and videos is in​your accoun...

Keith: Dec 1, 1:13am

Join a NameValueCollection into a querystring in C#

Well with a lamba expression, this​is what I came up​with:

?!code:csharp...

Gustaf Lindqvist: Nov 30, 4:38pm

Generated in about 0.353s.

(Used 8 db queries)

mobile phone