dongzhuang1923 2017-11-16 14:15
浏览 206
已采纳

如何在不创建前者对象的情况下,从另一个不同的类方法静态调用类的非静态方法?

I'm using PHP 7.1.11

Consider below code :

<?php
  class A {
    function foo() {
      if (isset($this)) {
        echo '$this is defined (';
        echo get_class($this);
        echo ")
";
      } else {
        echo "\$this is not defined.
";
      }
    }
  }

  class B {
    function bar() {
      A::foo();
    }
  }

  $a = new A();
  $a->foo();

  A::foo();
  $b = new B();
  $b->bar();

  B::bar();
?>

Output of above code :

$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.

Except the first line in the output the next three lines of output have been generated by calling the non-static method foo() which is present in class A statically(i.e. without creating an object of class A).

Someone please explain me how is this happening?

How does the non-static method from another class is getting called statically from the class/ object of class under consideration(i.e. class B here)?

Thank You.

  • 写回答

1条回答 默认 最新

  • dqbr37828 2017-11-16 14:35
    关注

    Note: PHP is very loose with static vs. non-static methods

    But: Methods which are not static should NOT be called statically (even if PHP is tolerant). Why?

    If a method is not static, this usually means that it is depending on the state of an instance, because otherwise it could be made static.

    Sometimes a non-static method is not dependent on an instance and therefore a program still works, because this method could be static. But you never should do this.

    Furthermore - if you turn on error reporting, PHP will also tell you this:

    $this is defined (A)
    Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 25
    $this is not defined.
    Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 18
    $this is not defined.
    Deprecated: Non-static method B::bar() should not be called statically in [...][...] on line 29

    Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 18
    $this is not defined.

    The Deprecated also means: Just because PHP still allows this, it will most probably be removed in future PHP updates.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 请教一下c语言的代码里有一个地方不懂
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了