本文介绍了为什么PHP将上下文分配给静态方法调用而没有给出E_STRICT通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP5.4(在5.5中也出现)中遇到了一些非常奇怪的行为.基本上,我是静态地调用一个非静态方法,并且我没有得到我肯定应该得到的E_STRICT错误.

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() {}
}

现在,如果我这样做:

A::iAmNotStatic();

然后我按预期得到错误Strict standards: Non-static method A::iAmNotStatic() should not be called statically.

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

但是,如果我这样做(将A指派为B的父母)

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

然后PHP决定没问题,我有一个具有相同父类(A)的对象($ b),让我们将其作为iAmNotStatic的上下文".

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 :)

推荐答案

在第一种情况下,由于从外部空间调用非静态方法,因此没有对象上下文.但在第二种情况下,您拥有对象上下文,因为$this将引用B的实例-因此,PHP将发现对象上下文存在,因此,它是一个非-非静态方法的静态调用(一切正常).如果您对通过::通话感到犹豫-那么,我想您应该提醒一下,例如parent::method()是有效的通话. IE.引用方式不是这里的问题.

In first case, you have no object context since you're calling your non-static method from outer space. But in second case, you have object context since $this will refer to instance of B - and, therefore, PHP will find that object context exists, and, therefore, it is a non-static call of non-static method (everything is ok). If you're hesitating about call via :: - then, I think, you should remind that, for example, parent::method() is a valid call. I.e. referring way is not the problem here.

更具体地说:

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

所以您会看到自foo()继承以来的类B.

so you'll see class B as expected since foo() was inherited.

这篇关于为什么PHP将上下文分配给静态方法调用而没有给出E_STRICT通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:08