php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #20089 Calling static method from instance method results in invalid $this
Submitted: 2002-10-25 11:08 UTC Modified: 2004-04-25 18:12 UTC
From: dougqh at incogen dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 4.2.3 OS: *
Private report: No CVE-ID: None
 [2002-10-25 11:08 UTC] dougqh at incogen dot com
Here is an example ...

<?php

class Foo
{
   function Foo()
   {
      $this->class = 'foo';
   }   

   function doCall()
   {
      return Bar::staticFunction();
   }
   
};

class Bar
{
   function staticFunction()
   {
      if ( isset( $this ) )
      {
         print 'This isset <br />';
         print_r( $this );         
      }
      else
      {
         print 'Call as a static <br />';
      }
   }   
};

$foo =& new Foo();
$foo->doCall();

?>

Note an instance of Foo is calling a static method of Bar.  Bar does a test to see if $this is set.  $this should not be set, since the method was statically invoked.  Unfortunately, $this is set and its the instance of Foo that made the call to the static method of Bar.

This bug makes writing methods that work both as static methods and instance methods virtually impossible.  It is also extremely unsafe to allow Bar to access the member variables of Foo.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-10-25 12:03 UTC] derick@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

Also, this was discussed before (in both the bugdatabase and on the developer mailinglist) and this behavior will not be changed in the near future.
 [2002-10-25 12:53 UTC] dougqh at incogen dot com
Maintaining $this within a class even when a static method is called is reasonable, but allowing a $this to exist that is not from the proper class is awful.  At the very least, I think this problem should be better documented.  A warning in the manaul entry for :: (http://www.php.net/manual/en/keyword.paamayim-nekudotayim.php) would be good, since that page currently incorrectly indicates that $this will not be available when a static method call is made.  I see a user note has been added, but something more visible would be preferable.
 [2004-04-25 18:12 UTC] helly@php.net
Not on PHP5: In a stattically called method there cannot be a $this because it is a local variable generated by the engine. The behavior of PHP 4 is wrong and is there only because there simply was no way to implement it correct. One of the reasons it could not be done correct is the lack of real static methods.




 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Sat Apr 04 05:01:22 2020 UTC