0

I ran into some very strange behaviour on PHP5.4 (also present in 5.5). Basically, I am calling a non-static method statically and I am not getting an E_STRICT error where I definitely should be getting one.

<?php
error_reporting(E_ALL);
class A
{
    public function iAmNotStatic() {}
}

Now, if I do this:

A::iAmNotStatic();

Then I get the error as expected Strict standards: Non-static method A::iAmNotStatic() should not be called statically.

And also, if I make the call from object context, I also get the same error (as expected)

class B 
{
    public function __construct() {
        A::iAmNotStatic();
    }
}

$b = new B(); // error here, as expected

However, if I do this (assign A to be the parent of B):

class B extends A
{
    public function __construct() {
        A::iAmNotStatic();
    }
}

$b = new B(); // no error 

Then PHP decides that "no problem, I have an object ($b) with the same parent class (A), let's just make it the context for iAmNotStatic".

So, is this a feature or a bug and what might be the purpose of this confusing (undocumented?) behaviour? Thanks :)

4

1 回答 1

1

在第一种情况下,您没有对象上下文,因为您是从外太空调用非静态方法。但是在第二种情况下,您对象上下文,因为$this将引用 - 的实例B,因此,PHP 会发现对象上下文存在,因此,它是对非静态方法的非静态调用(一切正常)。如果您对 call via 犹豫不决::- 那么,我认为,您应该提醒一下,例如, parent::method() 这是一个有效的呼叫。即参考方式不是这里的问题。

更加具体:

class A
{
   public function foo()
   {
      echo('foo called, class: '. get_class($this).PHP_EOL);
   }
}

class B extends A
{
   public function __construct()
   {
      A::foo();
   }
}

$b=new B(); //foo called, class: B 

所以你会看到类B如预期的那样,因为foo()它被继承了。

于 2013-09-11T10:27:26.630 回答