PHP中的静态方法 [英] Static methods in PHP

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

问题描述

为什么在PHP中您可以通过某个类的实例而不是仅通过类型名称访问静态方法?

Why in PHP you can access static method via instance of some class but not only via type name?

更新:我是.net开发人员,但我也与php开发人员一起工作.最近,我发现这一刻涉及从实例调用的静态方法,并且无法理解为什么它会有用.

UPDATE: I'm .net developer but i work with php developers too. Recently i've found this moment about static methods called from instance and can't understand why it can be usefull.

示例:

class Foo
{
    public static Bar()
    {
    }
}

我们可以接受这样的方法:

We can accept method like this:

var $foo = new Foo();
$foo.Bar(); // ??????

推荐答案

在PHP中

例如,使用new关键字实例化该类;

the class is instantiated using the new keyword for example;

$MyClass = new MyClass();

和静态方法或属性可以通过使用范围解析运算符或对象引用运算符进行访问.例如,如果类MyClass包含静态方法Foo(),则可以通过任何一种方式访问​​它.

and the static method or properties can be accessed by using either scope resolution operator or object reference operator. For example, if the class MyClass contains the static method Foo() then you can access it by either way.

$MyClass->Foo();

MyClass::Foo()

唯一的规则是静态方法或属性不在对象上下文之内.例如,不能在静态方法中使用$this.

The only rule is that static methods or properties are out of object context. For example, you cannot use $this inside of a static method.

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

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