John Wells wrote:
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, ... Why?  The reason is SCOPE.
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.

As an OOP programmer, I would expect the scope search to be as follows:

  1. LOCAL: current method
  2. THIS: current instance ($this)
  3. SELF: current class & parent classes, in order of inheritance
  4. GLOBAL: globals

I really hate globals because it defeats my style of encapsulation. If the search for my constant follows the search I've listed above, self would never be necessary unless you wanted to pinpoint "3" directly. Under this same line of thinking, though, '$this->' really shouldn't be be necessary either unless you wanted to clarify local vs this for same-named variables.

And is "self::" really a lot of boiler-plate?  Really??
YES.

$x = ($y == self :: MY_CONSTANT || $y == self :: MY_CONSTANT2);
vs
$x = ($y == MY_CONSTANT || $y == MY_CONSTANT2);

My philosophy is that the more code which is written, the greater the probability of bugs. Writing less code means less to read and less to read means easier to comprehend.

From what I can tell, PHP only uses 1) LOCAL and 4) GLOBAL scope unless you specifically use $this or self, but I just don't think those should be necessary. Other than "that's just the way it is", why IS it necessary to use $this and self?

Dante

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

Reply via email to