Incorrect PHP code working fine

I have the following code:

class A { public function methodB() { // do something return 1; } } $a = A::methodB(); 

It should never work and it works on this machine! He really returns 1. Indeed, I swear I'm not drunk.

Of course, if I run it on my machine or on a production server, this will not work. Because you cannot call non-static methods like static. The class must first be created.

I was worried about that. Thought today, when I created a separate working machine for testing the project, I again got the environment in which this code works.

Everything is getting worse - I have developers on the team who still do not understand the difference between static and non-stationary methods. As a result, they have code that works fine on their machine, but it doesn't work in other environments.

WHY does it work? I want this code to fail. This should not work.

The configuration of the machine where it works is as follows:

vagrant @ vagrant-ubuntu-trusty-32: / var / www / apotheke $ php -v PHP 5.6.17-3 + deb.sury.org ~ trusty + 1 (cli) Copyright (c) 1997-2015 PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, Zend Technologies

Indeed, I feel so stupid. Did I miss something?

+5
source share
2 answers

The above code is valid in PHP 5. From the docs :

In PHP 5, calling non-static methods statically generates an E_STRICT level E_STRICT .

If you include a severe error reporting a warning, for example, the following:

Strict PHP standards: non-static method A :: methodB () should not be called statically in php shell code on line 1

Note that the method will still run and return a value.

It is deprecated in PHP 7 and is not recommended for use.

In PHP 7, calling static methods is statically deprecated and will generate an E_DEPRECATED warning. Support for calling non-static methods may be statically removed in the future.

+4
source

You get the following warning:

Strict standards: non-static method A :: methodB () should not call static

but PHP assumes you want to run it anyway, so it does it.

To prevent this, you can change your method to:

 class A { public function methodB(){ if(isset($this)){ // do something return 1; } } } 

The E_STRICT error will be E_STRICT anyway (which you can disable), but PHP does not assume that you should run it anyway.

+2
source

Source: https://habr.com/ru/post/1240841/


All Articles