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

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

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.

图片转代码服务由CSDN问答提供 功能建议

我正在使用 PHP 7.1.11 < p>考虑下面的代码:

 &lt;?php 
 class A {
 function foo(){
 if if(isset($ this)){
 echo  '$ this is defined('; 
 echo get_class($ this); 
 echo“)
”; 
} else {
 echo“\ $ this not a defined。
”; 
} \  n} 
} 
 
 B类{
功能栏(){
 A :: foo(); 
} 
} 
 
 $ a =新A(); 
 $ a  - &gt; foo(); 
 
 A :: foo(); 
 $ b = new B(); 
 $ b-&gt; bar(); 
 
 B :: bar();  
?&gt; 
   
 
 

输出上述代码:

  $ this is defined(A)
  $ this未定义。
 $未定义。
 $未定义。
   
 
 

除输出中的第一行外接下三行 通过调用静态方法 foo()生成输出,该方法静态存在于 class A 中(即不创建 class A的对象)。

有人请说明 告诉我这是怎么回事?

如何从正在考虑的类的类/对象中静态调用来自另一个类的非静态方法(例如 class B )?

谢谢。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqbr37828
    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.

    点赞 评论

相关推荐