class Document {
const CONST_SERVER_TIME = time();
const CONST_PHP_SELF = mycleanupfunction($_SERVER['PHP_SELF']);
const CONST_WHATEVER = 'string' . 'concatenation';
//...
}
Constants in a class have to be a simple string.
class Document {
const CONST_SERVER_TIME;
const CONST_PHP_SELF;
const CONST_WHATEVER;
//...
function __construct()
{
self::CONST_SERVER_TIME = time();
self::CONST_PHP_SELF = mycleanupfunction($_SERVER['PHP_SELF']);
self::CONST_WHATEVER = 'string' . 'concatenation';
}
}
If PHP 5.4 or PHP 6 would allow us to set constants in classes like my
original post showed, that would be great.
But that's not how constants work. You might have a design issue.
Why do you think you can't use variables instead?
Perhaps you want static properties? Since you don't explain what
you're really trying to accomplish, we can't really diagnose the
problems with your overall goal.
Static properties example:
<?php
class MyDate {
private static $date = NULL;
public function __construct() {
/* Initialize date only once */
if (!isset(self::$date)) {
self::$date = time();
}
}
public function setDate($date) {
self::$date = $date;
}
public function printDate() {
echo date('Y-m-d h:ia', self::$date), "\n";
}
}
$date = new MyDate;
$date->setDate(strtotime('next wednesday 5pm'));
$date->printDate();
/* Outputs the same date as above */
$newDate = new MyDate;
$newDate->printDate();
/* Fatal error */
$date->time = time();
?>
See: <http://php.net/manual/en/language.oop5.static.php>
If you want more help with OOP theory in general, a better place
to ask would probably be <news:comp.programming>.
--
Curtis Dyer
<? $x='<? $x=%c%s%c;printf($x,39,$x,39);?>';printf($x,39,$x,39);?>
While I'm wary of refering to patterns as solutions or templates
rather than as classifications of implemented code, this topic is an
exception.....This is what the singleton pattern solves.
C.
I must admit that I misread your post and thought you were talking
about class properties.
This is because constants have global scope and so your example makes
no sense.
From the manual:
"Like superglobals, the scope of a constant is global. You can access
constants anywhere in your script without regard to scope."
Use variables instead, because these values above _are_ variables, not
constants.
Micha