On 5/9/06, D. Dante Lorenso <[EMAIL PROTECTED]> wrote:
Does anyone know if it's possible to reference class constants or static
variables without having to use 'self::' all the time?
No, and the answer is actually in your example. Copy-and-paste all of
your example code into one file, and just change the second class A to
B so that there isn't a class conflict. Then create an instance of A,
and B, and call both test() methods. You'll get the following result:
111
Why? The reason is SCOPE.
A::test() echos twice, the first for the class constant MY_CONSTANT,
and the second echo's the *global* MY_CONSTANT. Then B::test() echos
the *global* MY_CONSTANT again.
As wonderful as PHP is, it can't read your mind. So if you're looking
for a constant or variable, PHP needs to know where to look. If you
don't specify "self::', PHP will look in the global scope, as it did
in your code example. If you want it to look within your classes, you
need to *tell* it so.
And is "self::" really a lot of boiler-plate? Really??
John W
class A {
const MY_CONSTANT = true;
public function test() {
echo self :: MY_CONSTANT; // works
echo MY_CONSTANT; // doesn't work
}
}
I don't think it is possible, but why not? Can zend/php make it work?
Seems it could since this works:
define('MY_CONSTANT', true);
class A {
public function test() {
echo MY_CONSTANT; // works
}
}
It's just annoying my how much boiler-plate I have to write all the time.
Dante
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php