Why is this legal in PHP?
<?php
class Foo {
public function test() {
echo "hello\n";
}
}
Foo::test();
?>
test() is a non-static function but I can access it without an instance.
It's legal, but generally frowned upon, until you reference $this in your statically called method which will throw a fatal error.
I believe it's because of backwards compatibility. In PHP4 you didn't have the static keyword for methods (still looking for reference, but so far this is all I've found http://us2.php.net/manual/en/language.oop5.static.php). This way, PHP4 code can still run without a problem.
It is better practice to declare your static functions as such and if you turn on E_STRICT you'll see a notice about this.
error_reporting(E_ALL | E_STRICT);
Update: well, this is the best I've found http://bugs.php.net/bug.php?id=34990 and http://bugs.php.net/bug.php?id=47891.
From the PHP Manual:
Calling non-static methods statically
generates an E_STRICT level warning.
This works because you have not enabled the E_STRICT error level. Once enabled PHP will stop letting you to do this.
I don't believe that you can access a method of a class with out a instance of the object.
Related
I have a web application that I just updated from 5.3 to 5.5 on my server and i get around 200-300 errors like below. I understand this is a deprecation error and is it possible to solve all in one go and not hide the errors?
Strict standards: Non-static method xyz() should not be called statically.
Calling non-static methods statically generates an E_STRICT level warning.
Function xys is not static, but is clled statically. See difference below.
<?php
// Calling non-static function, first create object by class
$foo = new Foo();
$foo->xyz();
// Calling static function (you are doing this)
Foo::xyz();
?>
You should define your function like this. Find where xyz is defined.
public static function xyz(){}
Then it wont throw strict standard error. Just add static to your function and all errors will be gone.
You don't have to change it in all 200 files. This function is just called in 200 files. That dosen't meen that you have bug in all of them.
NOTE: from docs
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
So, if your are using $this in function xyz, you have to use my first example. Then it means fixing all 200 files.
See docs for static keyword.
Just make the function static.
The fix is a simple one , but it has to done in all places where you called a static method that way. I think there is no other way.
I was reading a book about PHP when I ran into a strange part of code:
class Employee {
public function show() {
echo "show launched\n";
}
}
Employee::show();
I came from C++ so I was going to bet this code wouldn't work. This is why I tested it.
And it worked, showing "show launched" (omg, am I drunk?)!
It seems to be breaking the concept that method of class can be called without instantiation of class.
What is the point then of static identifier in classes?
Are all public functions static too? Really, what am I missing?
Thanks in advance.
Addition:
Just a notice.
I found that in this book.
Pages 178-179 and it's given as correct example (if I'm right)
Yeah that would work but with a warning. You may have turned off your error reporting on PHP by the way...
Strict standards: Non-static method Employee::show() should not be
called statically
Adding a static keyword before the function definition would make the warning dissappear.
Below code works without a warning..
<?php
class Employee {
public static function show() { //<----- Added the static keyword.
echo "show launched\n";
}
}
Employee::show();
To answer your question...
It seems to be breaking the concept that method of class can be called
without instantiation of class.
Yeah that is correct, that's why you are getting a pretty clear cut warning as I showed you earlier. You know what a warning does right ? ;). Something that should not be done.
From the PHP Docs..
Calling non-static methods statically generates an E_STRICT level
warning.
Source
It has different behavior related on php version. PHP 4 did not have a static keyword (in function declaration context) but still allowed methods to be called statically with ::. This continued in PHP 5 for backwards compatibility purposes.
However with the changes in the object model with PHP 5 - the static keyword has been introduced.
And then since PHP 5.1.3 you get proper strict standard warnings about those like:
Strict Standards: Non-static method Employee::show() should not be called statically in ...
I think it depends on php version you are using. This feature is deprecated in the new php version and will be removed in the future versions.
this will not work and you will get error when using the latest php versions.
I am using PHP 5.5.9-1+sury.org~precise+1 (cli) (built: Feb 13 2014 15:53:53)
and if turn errors on and put your code as it is.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
class Employee {
public function show() {
echo "show launched\n";
}
}
Employee::show();
?>
This is error message I am getting.
**Strict Standards: Non-static method Employee::show() should not be called statically in /var/www/test/index.php on line 19
show launched**
The Code Works you will get a Warning
Strict standards: Non-static method Employee::show() should not be called statically
Just add the static keyword in the function like public static function show()
In the following code, nonStatic() is not a static method. Even then I am able to access it without creating an object (in a static way). Could anyone please help me in understanding as this is not possible in other languages like Java?
<?php
class MyClass
{
function nonStatic() {
echo "This can be printed";
}
}
MyClass::nonStatic(); // This can be printed
It's allowed, but it generates an E_STRICT warning:
Error #: 2048, Error: Non-static method MyClass::nonStatic() should not be called statically, assuming $this from incompatible context
In the earlier OO implementations of PHP this was silently allowed, but better practices have since been adopted.
The opposite works without a hitch though:
class Test
{
function foo()
{
echo $this->bar();
}
static function bar()
{
return "Hello world\n";
}
}
$x = new Test;
$x->foo();
This prints Hello world.
It seems as though the developers of PHP didn't see any value in disallowing static access of non-static methods. This is just one of those idiosyncratic features of PHP that doesn't really serve a purpose. It certainly is bad programming practice to call a non-static method statically, but in PHP it is possible. Maybe in a future version of PHP they will disallow this, but for now, it's just part of the language.
Edit:
Thankfully, the opposite is not allowed - you cannot call a static method from an object context. As Jack pointed out below, you can call a static method from an object context - hardly a best practice in the OOP paradigm, but it's allowed.
Not sure, probably some PHP magic (it's a bit like that sometimes), but you shouldn't do it.
Read more here http://php.net/manual/en/language.oop5.static.php
They also show a similar example, but note:
Calling non-static methods statically generates an E_STRICT level warning meaning this magic ability may disappear in future versions. So don't do it :)
What is the difference between these two pieces of code?
class something {
static function doit() {
echo 'hello world';
}
}
something::doit();
and the same but without the static keyword
class something {
function doit() {
echo 'hello world';
}
}
something::doit();
They both work the same is it better to use the static keywords? Am i right in understanding that it doesn't instantiate the class if you use the static method?
The second example is technically incorrect - if you turn on E_STRICT error reporting you'll see that PHP is actually throwing an error.
PHP Strict Standards: Non-static
method something::doit() should not be
called statically in...
In other words, it's being nice and letting you call the function anyway.
In addition to the other valid answers, the reason for the 2nd example working is also due to a quirk in how PHP handles objects and calls (Besides PHP 4 compatibility). Calling a non-static declared method statically from within another instance will let you access class methods on other classes as if they were local. To understand, let's take an example:
class A {
public function foo() {
echo get_class($this) . "\n";
}
}
class B {
public function bar() {
A::foo();
}
}
$a = new a();
$a->foo(); // "A"
$b = new B();
$b->bar(); // "B"
Did you see what happened there? Because you called the A::foo() method from within another class's instance, PHP treated the call as if it was on the same instance. Note that there is no relationship between A and B other than the fact that B calls A. Within A->foo(), if we did $this instanceof A (or $this instanceof self), it would fail and return false! Quite unusual...
Now, I first thought it was a bug, but after reporting it, it's apparently as designed. It's even in the docs.
Note that this will not work with E_STRICT mode enabled. It also will not work if you declare a method as static.
The difference is that static functions can be used without having to create an instance of the class.
Have a look at this great PHP OOP beginner tutorial here. It explains in more detail with an example under the Static Properties and Methods section.
Second bit shouldn't work as you should call it by
$something = new something();
$something->doit();
Static functions allows you to call a function within a class without consturcting it.
So basically if you have a class to handle users, so a function that logs the user in should be a static function, as in the constructor of that class you will probably gather the user information and you cannot do so without logging him in.
Your second example is wrong. Using a static method does not create an instance of the class. Your second example should look like this:
$x = new something();
$x->doit();
Static methods should be declared static for minimum two reasons:
a) when using E_STRICT error_reporting, calling non static method as static will generate error:
Strict standards: Non-static method something::doit() should not be called statically
b) based on keyword static some IDE's filter method possible to run at auto-complete.
Her is my code:
class MyClass
{
public $prop;
public function method ()
{
echo $this->prop;
}
}
Then somewhere in the code, accidently:
MyClass::method();
I would expect to have an interpretation error about the above line, because the called method is not static. Instead, the method was called, and I received an exception about $prop not existing. So i understand that the method was called as a static method, even though it's not.
Does it work this way? (Why the hell? )
Calling non-static methods statically generates an E_STRICT level warning.
http://php.net/manual/en/language.oop5.static.php
I suppose you have E_STRICT warnings suppressed. It works (likely for legacy reasons), but it's not recommended.
For legacy reasons, any class method could be called statically even if it wasn't declared static, because you previously couldn't declare them as such. In those cases, $this would simply refer to nothing because it's not an object-context variable.
In PHP 5 you get an E_STRICT warning for calling non-static methods statically (as you just did).