为什么PHP在对象上下文中使用静态方法? [英] Why PHP uses static methods in object context?

查看:111
本文介绍了为什么PHP在对象上下文中使用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(例如,实际上,这是我的真实代码):

I have the following code (like, for real, this is my real code) :

<?php
class Foobar
{
  public static function foo()
  {
    exit('foo');
  }
}

当我运行$foobar = new FooBar; $foobar->foo()时,它会显示foo.

When I run $foobar = new FooBar; $foobar->foo() it displays foo.

为什么PHP会尝试在对象上下文中使用静态方法?有办法避免这种情况吗?

Why would PHP try to use a static method in an object context ? Is there a way to avoid this ?

好的,你们没听懂我的问题:我知道静态方法和非静态方法之间的区别以及如何调用它们.这就是我的全部观点,如果我调用$foobar->foo(),为什么PHP会尝试运行静态方法?

Ok you guys didn't get my problem : I know the differences between static and non static methods and how to call them. That's my whole point, if I call $foobar->foo(), why does PHP tries to run a static method ?

注意:我运行PHP 5.4.4,将错误报告到E_ALL.

Note : I run PHP 5.4.4, error reporting to E_ALL.

推荐答案

要调用静态方法,请不要使用:

To call a static method, you don't use:

$foobar = new FooBar;
$foobar->foo()

您致电

FooBar::foo();

PHP手册说...

The PHP manual says...

将类属性或方法声明为静态使其可以访问 无需实例化类.宣告为 不能使用实例化的类对象访问static(尽管 静态方法可以).

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

这就是为什么您可以在实例上调用该方法的原因,即使这不是您打算执行的操作.

This is why you are able to call the method on an instance, even though that is not what you intended to do.

无论您是静态调用静态方法还是在实例上调用静态方法,都无法在静态方法中访问$this.

Whether or not you call a static method statically or on an instance, you cannot access $this in a static method.

http://php.net/manual/en/language.oop5. static.php

您可以检查一下自己是否处于静态环境,尽管我会怀疑这是否过于矫...……

You can check to see if you are in a static context, although I would question whether this is overkill...

class Foobar
{
  public static function foo()
  {
    $backtrace = debug_backtrace();
    if ($backtrace[1]['type'] == '::') {
      exit('foo');
    }
  }
}

另一条注释-我相信,即使在实例上调用该方法,该方法始终在静态上下文中执行.如果我错了,我很乐意对此进行纠正.

One additional note - I believe that the method is always executed in a static context, even if it is called on an instance. I'm happy to be corrected on this if I'm wrong though.

这篇关于为什么PHP在对象上下文中使用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆