$var::staticfunction() OK but $this->var::staticfu

2019-07-23 13:53发布

问题:

In PHP, a static member or function can be accessed so long as the class name is a valid object or a string. This is mostly true. When the class name string is a property of an object, it can't be used directly. It must be copied to a simple variable before it can be used to access a static member. Here's an example:

class Foo {
  protected $otherclass='Bar'; //string!

  function out(){
    $class=$this->otherclass;
    echo $class::ALIAS;  //Where everyone knows your name.
  }

  function noout_err(){
    echo $this->otherclass::ALIAS; //syntax error, unexpected '::' 
  }
}

class Bar {
  const ALIAS='Where everyone knows your name.'
}

This quirk has bothered me for a while now. So I've been wondering:

  • Is this a common limitation among OOP languages?
  • Can someone familiar with the internals of PHP explain why $this->classname::somefunction() is not desirable syntax?

This isn't meant to provoke a storm of 'because php sux' comments. I'm well aware of the language's peculiarities. I'd just like to know if there is a reason for this one other than 'it just grew that way'.

回答1:

It is a limitation indeed and there's a reason for it: The :: scope operator has an higher precedence over -> which means that:

$this->otherclass::ALIAS;

will be read as:

($this->(otherclass::ALIAS));

therefore triggering the error.

This is actually a feature that PHP inherited probably by C++.



回答2:

Yeah, you can't do this, and there's no explicit reason for it. There's simply no syntax, messing up the grammar, to provide for this extreme edge case for which you've already demonstrated that there's a trivial workaround.

I'd hardly go so far as to call it a "limitation", and it's certainly no "quirk". PHP can't bake bread, either.

Really, if you see the code $this->classname::somefunction(), does it immediately make intuitive sense to you? Nah. It's good that you can't do this.



标签: php static