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'.
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++.
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.
Related
I know there are a couple of similar questions here in StackOverflow like this question.
Why is overriding method parameters a violation of strict standards in PHP?
For instance:
class Foo
{
public function bar(Array $bar){}
}
class Baz extends Foo
{
public function bar($bar) {}
}
Strict standards: Declaration of Baz::bar() should be compatible with
that of Foo::bar()
In other OOP programming languages you can. Why is it bad in PHP?
In OOP, SOLID stands for Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion.
Liskov substitution principle states that, in a computer program, if Bar is a subtype of Foo, then objects of type Foo may be replaced with objects of type Bar without altering any of the desirable properties of that program (correctness, task performed, etc.).
In strong-typed programming languages, when overriding a Foo method, if you change the signature in Bar, you are actually overloading since the original method and the new method are available with different signatures. Since PHP is weak typed, this is not possible to achieve, because the compiler can't know which of the methods you are actually calling. (hence the reason you can't have 2 methods with the same name, even if their signatures are different).
So, to avoid the violation of Liskov Substituition principle, a strict standard warning is issued, telling the programmer something might break due to the change of the method signature in the child class.
I know I am late to the party but the answers don't really spell out the actual problem.
The problem is PHP doesn't support function/method overloading. It would be difficult to support function overloading in an untyped language.
Hinting helps. but in PHP it is very limited. Not sure why. For example you cannot hint a variable is an int or Boolean yet array is fine. Go figure!
Other object orientated languages implement this using function overloading. Which is to say the signature of the function is obviously different.
So for example if the following was possible we would not have an issue
class Foo
{
public function bar(Array $bar){
echo "Foo::bar";
}
}
class Baz extends Foo
{
public function bar(int $bar) {
echo "Baz::bar";
}
}
$foo = new Baz();
$bar = new Baz();
$ar = array();
$i = 100;
$foo->bar($ar);
$bar->bar((int)$i);
would output
Foo::bar
Baz::bar
Of course when it came to constructors the php developers realised they have to implement it, Like it or not! So they simply suppress the error or not raise it in the first case.
Which is silly.
An acquaintance once said PHP implemented objects only as a way of implementing namespaces. Now I am not quite that critical but some of the decisions taken do tend to support that theory.
I always have maximum warnings turned on when developing code, I never let a warning go by without understanding what it means and what the implications are. Personally I don't care for this warning. I know what I want to do and PHP doesn't do it right. I came here looking for a way to selectively suppress it. I haven't found a way yet.
So I will trap this warning and suppress it myself. Shame I need to do this. but I am strict about STRICT.
You can override parameters, but the signature should match. If you had put Array out in front of $bar, there would be no problem.
For example, if you had added an additional parameter, there would be no problem, provided the first parameter had the same type hinting. This is good practice in any language.
Because you declared on Foo that $bar should be of type array, while in the extending Bar, $bar's type isn't declared.
This isn't an error, it's a warning. You should make the method definition compatible with the original, base class. You can, however, safely ignore it if you know what you're doing (and only if you know what you're doing!!!)
I've seen both used in documentation of a PHP library (seemingly interchangeably) and was wondering if there's a method to the madness and a time when each should be used? (Or if they mean something different, a nuance which I've therefore missed in the documentation)
Examples:
ClassName#foo() // a method
ClassName::bar() // a method
ClassName::baz // a property
I've not (yet) seen anybody try to use ClassName#qux for a property but perhaps that's possible too!
Hopefully this thread will help to set people on the straight and narrow!
Thanks in advance
P.S. it's hard searching Google for this. "#" = "hash" = "pound" and "::" = "double colon" = "T_PAAMAYIM_NEKUDOTAYIM"... and "hash" means something all of its own too, of course.
Edit: A further question is whether it is normal/correct to document properties and variables as ClassName::foo or ClassName::$foo (i.e. with or without a leading $)
Even for PHP, it's perverse, which is saying a lot. Don't ever do it in any context.
It is probably to disambiguate between actual static methods which can literally be called with Foo::bar(), and instance methods which require an object instance, like $foo->bar(). That's the only sensible explanation I can think of, and it's not an official standard in any context that I'm aware of.
I know there are a couple of similar questions here in StackOverflow like this question.
Why is overriding method parameters a violation of strict standards in PHP?
For instance:
class Foo
{
public function bar(Array $bar){}
}
class Baz extends Foo
{
public function bar($bar) {}
}
Strict standards: Declaration of Baz::bar() should be compatible with
that of Foo::bar()
In other OOP programming languages you can. Why is it bad in PHP?
In OOP, SOLID stands for Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion.
Liskov substitution principle states that, in a computer program, if Bar is a subtype of Foo, then objects of type Foo may be replaced with objects of type Bar without altering any of the desirable properties of that program (correctness, task performed, etc.).
In strong-typed programming languages, when overriding a Foo method, if you change the signature in Bar, you are actually overloading since the original method and the new method are available with different signatures. Since PHP is weak typed, this is not possible to achieve, because the compiler can't know which of the methods you are actually calling. (hence the reason you can't have 2 methods with the same name, even if their signatures are different).
So, to avoid the violation of Liskov Substituition principle, a strict standard warning is issued, telling the programmer something might break due to the change of the method signature in the child class.
I know I am late to the party but the answers don't really spell out the actual problem.
The problem is PHP doesn't support function/method overloading. It would be difficult to support function overloading in an untyped language.
Hinting helps. but in PHP it is very limited. Not sure why. For example you cannot hint a variable is an int or Boolean yet array is fine. Go figure!
Other object orientated languages implement this using function overloading. Which is to say the signature of the function is obviously different.
So for example if the following was possible we would not have an issue
class Foo
{
public function bar(Array $bar){
echo "Foo::bar";
}
}
class Baz extends Foo
{
public function bar(int $bar) {
echo "Baz::bar";
}
}
$foo = new Baz();
$bar = new Baz();
$ar = array();
$i = 100;
$foo->bar($ar);
$bar->bar((int)$i);
would output
Foo::bar
Baz::bar
Of course when it came to constructors the php developers realised they have to implement it, Like it or not! So they simply suppress the error or not raise it in the first case.
Which is silly.
An acquaintance once said PHP implemented objects only as a way of implementing namespaces. Now I am not quite that critical but some of the decisions taken do tend to support that theory.
I always have maximum warnings turned on when developing code, I never let a warning go by without understanding what it means and what the implications are. Personally I don't care for this warning. I know what I want to do and PHP doesn't do it right. I came here looking for a way to selectively suppress it. I haven't found a way yet.
So I will trap this warning and suppress it myself. Shame I need to do this. but I am strict about STRICT.
You can override parameters, but the signature should match. If you had put Array out in front of $bar, there would be no problem.
For example, if you had added an additional parameter, there would be no problem, provided the first parameter had the same type hinting. This is good practice in any language.
Because you declared on Foo that $bar should be of type array, while in the extending Bar, $bar's type isn't declared.
This isn't an error, it's a warning. You should make the method definition compatible with the original, base class. You can, however, safely ignore it if you know what you're doing (and only if you know what you're doing!!!)
Can I use it as a method name in my classes?
It appears to be a function: http://www.php.net/manual/en/ref.misc.php
But I see there listed some language constructs too, like die and exit.
When you can... you can, when you can't... you'll know :)
See a list of reserved words here http://php.net/manual/en/reserved.php and avoid them. Any good PHP IDE will warn you when you attempt to illegal-name your methods.
There's another issue. If you forget $this->Method() and you just use Method() in your class, it will work as it's defined as a function. This will lead to freak and hard to find bugs.
<?php
class Test {
function defined() {
return "Yes you can";
}
}
$x = new Test();
echo $x->defined();
Yes, you can. No, you shouldn't. Using the same name as built-in functions is never a good idea. The word defined has an established meaning in PHP, and nobody should have to think harder to figure out how your class is using (or abusing) the word in some specific context.
I'm pretty new to PHP, but I've been programming in similar languages for years. I was flummoxed by the following:
class Foo {
public $path = array(
realpath(".")
);
}
It produced a syntax error: Parse error: syntax error, unexpected '(', expecting ')' in test.php on line 5 which is the realpath call.
But this works fine:
$path = array(
realpath(".")
);
After banging my head against this for a while, I was told you can't call functions in an attribute default; you have to do it in __construct. My question is: why?! Is this a "feature" or sloppy implementation? What's the rationale?
The compiler code suggests that this is by design, though I don't know what the official reasoning behind that is. I'm also not sure how much effort it would take to reliably implement this functionality, but there are definitely some limitations in the way that things are currently done.
Though my knowledge of the PHP compiler isn't extensive, I'm going try and illustrate what I believe goes on so that you can see where there is an issue. Your code sample makes a good candidate for this process, so we'll be using that:
class Foo {
public $path = array(
realpath(".")
);
}
As you're well aware, this causes a syntax error. This is a result of the PHP grammar, which makes the following relevant definition:
class_variable_declaration:
//...
| T_VARIABLE '=' static_scalar //...
;
So, when defining the values of variables such as $path, the expected value must match the definition of a static scalar. Unsurprisingly, this is somewhat of a misnomer given that the definition of a static scalar also includes array types whose values are also static scalars:
static_scalar: /* compile-time evaluated scalars */
//...
| T_ARRAY '(' static_array_pair_list ')' // ...
//...
;
Let's assume for a second that the grammar was different, and the noted line in the class variable delcaration rule looked something more like the following which would match your code sample (despite breaking otherwise valid assignments):
class_variable_declaration:
//...
| T_VARIABLE '=' T_ARRAY '(' array_pair_list ')' // ...
;
After recompiling PHP, the sample script would no longer fail with that syntax error. Instead, it would fail with the compile time error "Invalid binding type". Since the code is now valid based on the grammar, this indicates that there actually is something specific in the design of the compiler that's causing trouble. To figure out what that is, let's revert to the original grammar for a moment and imagine that the code sample had a valid assignment of $path = array( 2 );.
Using the grammar as a guide, it's possible to walk through the actions invoked in the compiler code when parsing this code sample. I've left some less important parts out, but the process looks something like this:
// ...
// Begins the class declaration
zend_do_begin_class_declaration(znode, "Foo", znode);
// Set some modifiers on the current znode...
// ...
// Create the array
array_init(znode);
// Add the value we specified
zend_do_add_static_array_element(znode, NULL, 2);
// Declare the property as a member of the class
zend_do_declare_property('$path', znode);
// End the class declaration
zend_do_end_class_declaration(znode, "Foo");
// ...
zend_do_early_binding();
// ...
zend_do_end_compilation();
While the compiler does a lot in these various methods, it's important to note a few things.
A call to zend_do_begin_class_declaration() results in a call to get_next_op(). This means that it adds a new opcode to the current opcode array.
array_init() and zend_do_add_static_array_element() do not generate new opcodes. Instead, the array is immediately created and added to the current class' properties table. Method declarations work in a similar way, via a special case in zend_do_begin_function_declaration().
zend_do_early_binding() consumes the last opcode on the current opcode array, checking for one of the following types before setting it to a NOP:
ZEND_DECLARE_FUNCTION
ZEND_DECLARE_CLASS
ZEND_DECLARE_INHERITED_CLASS
ZEND_VERIFY_ABSTRACT_CLASS
ZEND_ADD_INTERFACE
Note that in the last case, if the opcode type is not one of the expected types, an error is thrown – The "Invalid binding type" error. From this, we can tell that allowing the non-static values to be assigned somehow causes the last opcode to be something other than expected. So, what happens when we use a non-static array with the modified grammar?
Instead of calling array_init(), the compiler prepares the arguments and calls zend_do_init_array(). This in turn calls get_next_op() and adds a new INIT_ARRAY opcode, producing something like the following:
DECLARE_CLASS 'Foo'
SEND_VAL '.'
DO_FCALL 'realpath'
INIT_ARRAY
Herein lies the root of the problem. By adding these opcodes, zend_do_early_binding() gets an unexpected input and throws an exception. As the process of early binding class and function definitions seems fairly integral to the PHP compilation process, it can't just be ignored (though the DECLARE_CLASS production/consumption is kind of messy). Likewise, it's not practical to try and evaluate these additional opcodes inline (you can't be sure that a given function or class has been resolved yet), so there's no way to avoid generating the opcodes.
A potential solution would be to build a new opcode array that was scoped to the class variable declaration, similar to how method definitions are handled. The problem with doing that is deciding when to evaluate such a run-once sequence. Would it be done when the file containing the class is loaded, when the property is first accessed, or when an object of that type is constructed?
As you've pointed out, other dynamic languages have found a way to handle this scenario, so it's not impossible to make that decision and get it to work. From what I can tell though, doing so in the case of PHP wouldn't be a one-line fix, and the language designers seem to have decided that it wasn't something worth including at this point.
My question is: why?! Is this a "feature" or sloppy implementation?
I'd say it's definitely a feature. A class definition is a code blueprint, and not supposed to execute code at the time of is definition. It would break the object's abstraction and encapsulation.
However, this is only my view. I can't say for sure what idea the developers had when defining this.
You can probably achieve something similar like this:
class Foo
{
public $path = __DIR__;
}
IIRC __DIR__ needs php 5.3+, __FILE__ has been around longer
It's a sloppy parser implementation. I don't have the correct terminology to describe it (I think the term "beta reduction" fits in somehow...), but the PHP language parser is more complex and more complicated than it needs to be, and so all sorts of special-casing is required for different language constructs.
My guess would be that you won't be able to have a correct stack trace if the error does not occur on an executable line... Since there can't be any error with initializing values with constants, there's no problem with that, but function can throw exceptions/errors and need to be called within an executable line, and not a declarative one.