The Magical (Dis)appearing $this Psuedo-Variable

Submitted by Matthew on Thu, 03/10/2016 - 20:24

At the office, we recently upgraded our staging server to PHP 7.  For the most part, this caused no problems at all and worked very well (and faster!).  But our event pages were failing, just giving us a white screen.  I looked in the "Recent log messages," and saw this:  "Error: Using $this when not in object context."  The code that triggered this error was a non-static class method that was being called statically from within a different class.  In PHP 5, this code only gives a "Deprecated" notice that non-static classes should not be called statically.

I was curious about this.  A non-static method called statically from another class's method is not within the scope of the instantiated object, yet PHP 5 just fudges it and gives you $this.  PHP 7 does not do this.

This change can be found in the PHP 7 changelog (http://php.net/ChangeLog-7.php):  "Removed scoped calls of non-static methods from an incompatible $this context."
    
PHP 7 still allows you to call non-static methods statically, as long as you are calling the method from another method within the same class; in fact, doing so doesn't even give you the deprecated notice. 

Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.