Voting

Please answer this simple SPAM challenge: seven minus three?
(Example: nine)

The Note You're Voting On

midir
8 years ago
There are a couple of tricks you can do with PHP's classes that programmers from C++, etc., will find very peculiar, but which can be useful.

You can create instances of classes without knowing the class name in advance, when it's in a variable:

<?php

$type
= 'cc';
$obj = new $type; // outputs "hi!"

class cc {
    function
__construct() {
        echo
'hi!';
    }
}

?>

You can also conditionally define them by wrapping them in if/else blocks etc, like so:

<?php

if (expr) {
    class
cc {
       
// version 1
   
}
} else {
    class
cc {
       
// version 2
   
}
}

?>

It makes up for PHP's lack of preprocessor directives. The caveat is that the if/else code body must have been executed before you can use the class, so you need to pay attention to the order of the code, and not use things before they're defined.

<< Back to user notes page

To Top