Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP wrong code works fine

I've the following code:

 class A  {
   public function methodB() 
  {
    // do something
     return 1;
  }
 }


$a = A::methodB();

It should never work and it works on that machine! It does return 1. Really, I swear I'm not drunk.

Of course if I run it on my machine or on production server it won't work. Because you can't call non-static methods like static. Class should always be instantiated at first.

I was worried about it. Thought today when I set up a separate working machine for testing the project I got again the environment there this code works.

Things get worse - I have developers in team who still doesn't get clearly the diference between Static and Non-static methods. As result they have code what works fine on their machine but it fails on any others environments.

WHY is it working? I want such code to fail. It shouldn't work.

The configuration of machine where it works is following:

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 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

Really, I feel so stupid. Do I miss something?

like image 749
Tebe Avatar asked Jan 18 '16 10:01

Tebe


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 warning.

If you turn on strict error reporting a warning such as the following will be output:

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

Please note 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 non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.

like image 92
topher Avatar answered Oct 11 '22 00:10

topher


You are getting following warning:

Strict standards: Non-static method A::methodB() should not be called statically

but PHP assumes you wanted to run it anyway so executes it.

To prevent it, you could change your method to:

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

The E_STRICT error will be thrown anyway (which you can disable), but PHP will not assume you meant to run it anyway.

like image 35
n-dru Avatar answered Oct 11 '22 00:10

n-dru